import React, { useState, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { useApp } from '@modelcontextprotocol/ext-apps/react';

function App() {
  const app = useApp();
  const [orgs, setOrgs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => { loadOrgs(); }, []);

  async function loadOrgs() {
    try {
      const result = await app.callTool('zendesk_list_organizations', {});
      const data = JSON.parse(result.content[0].text);
      setOrgs(data.organizations || []);
    } finally { setLoading(false); }
  }

  return (
    <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
      <h1>Organizations</h1>
      {loading ? <div>Loading...</div> : (
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr style={{ background: '#f5f5f5' }}>
            {['ID', 'Name', 'Domains', 'Tags', 'Created'].map(h => (
              <th key={h} style={{ padding: 12, textAlign: 'left' }}>{h}</th>
            ))}
          </tr></thead>
          <tbody>{orgs.map(o => (
            <tr key={o.id} style={{ borderBottom: '1px solid #eee' }}>
              <td style={{ padding: 12 }}>#{o.id}</td>
              <td style={{ padding: 12 }}>{o.name}</td>
              <td style={{ padding: 12 }}>{o.domain_names?.join(', ') || '-'}</td>
              <td style={{ padding: 12 }}>{o.tags?.slice(0, 3).join(', ') || '-'}</td>
              <td style={{ padding: 12 }}>{new Date(o.created_at).toLocaleDateString()}</td>
            </tr>
          ))}</tbody>
        </table>
      )}
      <div style={{ marginTop: 16 }}>Total: {orgs.length}</div>
    </div>
  );
}

createRoot(document.getElementById('root')!).render(<App />);
