const { useState, useEffect } = React;

const api = {
  get: async (url) => {
    const r = await fetch(url);
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(data.error || 'GET fehlgeschlagen');
    return data;
  },
  post: async (url, body) => {
    const r = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body || {})
    });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(data.error || 'POST fehlgeschlagen');
    return data;
  },
  put: async (url, body) => {
    const r = await fetch(url, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body || {})
    });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(data.error || 'PUT fehlgeschlagen');
    return data;
  },
  del: async (url) => {
    const r = await fetch(url, { method: 'DELETE' });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(data.error || 'DELETE fehlgeschlagen');
    return data;
  },
  upload: async (url, file, fields = {}) => {
    const fd = new FormData();
    fd.append('file', file);
    Object.entries(fields).forEach(([k, v]) => fd.append(k, v));
    const r = await fetch(url, { method: 'POST', body: fd });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(data.error || 'Upload fehlgeschlagen');
    return data;
  }
};

function App() {
  const [view, setView] = useState('dashboard');
  const [selectedBookId, setSelectedBookId] = useState(null);
  const [health, setHealth] = useState({ ollama: false });

  useEffect(() => {
    api.get('/api/health').then(setHealth).catch(() => setHealth({ ollama: false }));
  }, []);

  function openBook(id) {
    setSelectedBookId(id);
    setView('book');
  }

  return (
    <div className="min-h-screen">
      <header className="aok-green text-white p-4 shadow flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">📚 BookVault</h1>
          <div className="text-sm opacity-80">Buchprojekte · KDP · Versionen · Verkäufe</div>
        </div>
        <div className={`px-3 py-1 rounded text-xs ${health.ollama ? 'bg-green-700' : 'bg-gray-700'}`}>
          Ollama: {health.ollama ? '✓' : 'optional'}
        </div>
      </header>

      <nav className="bg-white border-b shadow-sm p-2 flex gap-2 overflow-x-auto">
        <NavButton active={view === 'dashboard'} onClick={() => setView('dashboard')}>Dashboard</NavButton>
        <NavButton active={view === 'books'} onClick={() => setView('books')}>Bücher</NavButton>
        <NavButton active={view === 'authors'} onClick={() => setView('authors')}>Autorenprofile</NavButton>
        <NavButton active={view === 'accounts'} onClick={() => setView('accounts')}>KDP-Accounts</NavButton>
      </nav>

      <main className="container mx-auto max-w-7xl p-6">
        {view === 'dashboard' && <Dashboard />}
        {view === 'books' && <Books onOpen={openBook} />}
        {view === 'authors' && <Authors />}
        {view === 'accounts' && <Accounts />}
        {view === 'book' && selectedBookId && <BookDetail bookId={selectedBookId} onBack={() => setView('books')} />}
      </main>
    </div>
  );
}

function NavButton({ active, onClick, children }) {
  return (
    <button onClick={onClick} className={`px-4 py-2 rounded ${active ? 'aok-green text-white' : 'hover:bg-gray-100'}`}>
      {children}
    </button>
  );
}

function Dashboard() {
  const [data, setData] = useState(null);

  useEffect(() => {
    api.get('/api/dashboard').then(setData).catch(console.error);
  }, []);

  if (!data) return <div>Lade Dashboard...</div>;

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold">Dashboard</h2>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Stat title="Bücher" value={data.counts.books} />
        <Stat title="Autorenprofile" value={data.counts.authors} />
        <Stat title="Manuskript-Versionen" value={data.counts.manuscripts} />
        <Stat title="Offene Aufgaben" value={data.counts.openTasks} />
      </div>

      <div className="card p-6">
        <h3 className="font-bold mb-4">Letzte Ereignisse</h3>
        <div className="space-y-2">
          {data.recentEvents.map(e => (
            <div key={e.id} className="border-b pb-2 text-sm">
              <span className="text-gray-500">{new Date(e.createdAt).toLocaleString('de-DE')}</span>
              <span className="ml-2">{e.message}</span>
            </div>
          ))}
          {data.recentEvents.length === 0 && <div className="text-gray-500">Noch keine Ereignisse.</div>}
        </div>
      </div>
    </div>
  );
}

function Stat({ title, value }) {
  return (
    <div className="card p-4 text-center">
      <div className="text-3xl font-bold aok-green-text">{value}</div>
      <div className="text-sm text-gray-600">{title}</div>
    </div>
  );
}

function Authors() {
  const [authors, setAuthors] = useState([]);
  const [form, setForm] = useState({
    displayName: '',
    legalName: '',
    bioShort: '',
    genreFocus: '',
    website: '',
    notes: ''
  });

  async function load() {
    setAuthors(await api.get('/api/authors'));
  }

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

  async function save() {
    await api.post('/api/authors', form);
    setForm({ displayName: '', legalName: '', bioShort: '', genreFocus: '', website: '', notes: '' });
    load();
  }

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold">Autorenprofile / Pseudonyme</h2>

      <div className="card p-6">
        <h3 className="font-bold mb-4">Neues Autorenprofil</h3>
        <div className="grid md:grid-cols-2 gap-4">
          <Input label="Anzeigename / Pseudonym" value={form.displayName} onChange={v => setForm({...form, displayName:v})} />
          <Input label="Realer Name intern" value={form.legalName} onChange={v => setForm({...form, legalName:v})} />
          <Input label="Genre-Fokus" value={form.genreFocus} onChange={v => setForm({...form, genreFocus:v})} />
          <Input label="Website" value={form.website} onChange={v => setForm({...form, website:v})} />
          <Textarea label="Kurz-Bio" value={form.bioShort} onChange={v => setForm({...form, bioShort:v})} />
          <Textarea label="Notizen" value={form.notes} onChange={v => setForm({...form, notes:v})} />
        </div>
        <button onClick={save} className="aok-green text-white px-4 py-2 rounded mt-4">Speichern</button>
      </div>

      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
        {authors.map(a => (
          <div key={a.id} className="card p-4">
            <h3 className="font-bold text-lg">{a.displayName}</h3>
            <p className="text-sm text-gray-600">{a.genreFocus}</p>
            <p className="text-sm mt-2">{a.bioShort}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

function Books({ onOpen }) {
  const [books, setBooks] = useState([]);
  const [authors, setAuthors] = useState([]);
  const [show, setShow] = useState(false);
  const [form, setForm] = useState({
    workingTitle: '',
    finalTitle: '',
    authorId: '',
    format: 'paperback',
    status: 'Idee',
    genre: '',
    plannedPublishDate: ''
  });

  async function load() {
    setBooks(await api.get('/api/books'));
    setAuthors(await api.get('/api/authors'));
  }

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

  async function create() {
    await api.post('/api/books', form);
    setForm({ workingTitle: '', finalTitle: '', authorId: '', format: 'paperback', status: 'Idee', genre: '', plannedPublishDate: '' });
    setShow(false);
    load();
  }

  async function remove(id, e) {
    e.stopPropagation();
    if (!confirm('Buchprojekt wirklich löschen?')) return;
    await api.del('/api/books/' + id);
    load();
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between">
        <h2 className="text-2xl font-bold">Bücher</h2>
        <button onClick={() => setShow(!show)} className="aok-green text-white px-4 py-2 rounded">+ Neues Buch</button>
      </div>

      {show && (
        <div className="card p-6">
          <h3 className="font-bold mb-4">Neues Buchprojekt</h3>
          <div className="grid md:grid-cols-3 gap-4">
            <Input label="Arbeitstitel" value={form.workingTitle} onChange={v => setForm({...form, workingTitle:v})} />
            <Input label="Finaler Titel" value={form.finalTitle} onChange={v => setForm({...form, finalTitle:v})} />
            <Select label="Autorname" value={form.authorId} onChange={v => setForm({...form, authorId:v})}
              options={[['', 'Nicht gesetzt'], ...authors.map(a => [a.id, a.displayName])]} />
            <Select label="Format" value={form.format} onChange={v => setForm({...form, format:v})}
              options={[['ebook','eBook'],['paperback','Taschenbuch'],['hardcover','Hardcover'],['all','Alle Formate']]} />
            <Select label="Status" value={form.status} onChange={v => setForm({...form, status:v})}
              options={['Idee','Entwurf','Lektorat','Cover','KDP vorbereitet','Veröffentlicht','Archiviert'].map(x => [x,x])} />
            <Input label="Genre" value={form.genre} onChange={v => setForm({...form, genre:v})} />
            <Input label="Geplantes Veröffentlichungsdatum" type="date" value={form.plannedPublishDate} onChange={v => setForm({...form, plannedPublishDate:v})} />
          </div>
          <button onClick={create} className="aok-green text-white px-4 py-2 rounded mt-4">Anlegen</button>
        </div>
      )}

      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
        {books.map(b => (
          <div key={b.id} onClick={() => onOpen(b.id)} className="card p-4 cursor-pointer hover:shadow-lg transition">
            <div className="flex justify-between gap-2">
              <h3 className="font-bold text-lg">{b.finalTitle || b.workingTitle}</h3>
              <span className="text-xs bg-gray-100 px-2 py-1 rounded h-fit">{b.status}</span>
            </div>
            <p className="text-sm text-gray-600">{b.author?.displayName || 'Kein Autorprofil'}</p>
            <p className="text-xs text-gray-500 mt-2">Format: {b.format} · Genre: {b.genre || '-'}</p>
            <p className="text-xs text-gray-500">Manuskripte: {b.manuscriptsCount} · Dateien: {b.assetsCount}</p>
            <p className="text-xs text-gray-500">Royalties: {Number(b.salesTotal || 0).toLocaleString('de-DE')} EUR</p>
            <button onClick={(e) => remove(b.id, e)} className="text-red-600 text-xs mt-3">löschen</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function BookDetail({ bookId, onBack }) {
  const [bundle, setBundle] = useState(null);
  const [tab, setTab] = useState('overview');

  async function load() {
    setBundle(await api.get('/api/books/' + bookId));
  }

  useEffect(() => { load(); }, [bookId]);

  if (!bundle) return <div>Lade Buch...</div>;

  const book = bundle.book;

  return (
    <div className="space-y-6">
      <button onClick={onBack} className="text-sm hover:underline">← Zurück zu Bücher</button>

      <div className="card p-6">
        <h2 className="text-2xl font-bold">{book.finalTitle || book.workingTitle}</h2>
        <p className="text-gray-600">{bundle.author?.displayName || 'Kein Autorprofil'} · {book.status}</p>
      </div>

      <div className="bg-white border rounded p-2 flex gap-2 overflow-x-auto">
        {[
          ['overview','Übersicht'],
          ['manuscripts','Manuskripte'],
          ['assets','Cover & Unterlagen'],
          ['kdp','KDP-Metadaten'],
          ['sales','Verkäufe'],
          ['tasks','Aufgaben'],
          ['export','Export']
        ].map(([k, label]) => (
          <button key={k} onClick={() => setTab(k)} className={`px-3 py-2 rounded ${tab === k ? 'aok-green text-white' : 'hover:bg-gray-100'}`}>
            {label}
          </button>
        ))}
      </div>

      {tab === 'overview' && <Overview bundle={bundle} />}
      {tab === 'manuscripts' && <Manuscripts bookId={bookId} items={bundle.manuscripts} onChange={load} />}
      {tab === 'assets' && <Assets bookId={bookId} items={bundle.assets} onChange={load} />}
      {tab === 'kdp' && <KdpMetadata bookId={bookId} kdp={bundle.kdp} onChange={load} />}
      {tab === 'sales' && <Sales bookId={bookId} items={bundle.sales} onChange={load} />}
      {tab === 'tasks' && <Tasks items={bundle.tasks} onChange={load} />}
      {tab === 'export' && <ExportPackage bookId={bookId} />}
    </div>
  );
}

function Overview({ bundle }) {
  return (
    <div className="grid md:grid-cols-2 gap-4">
      <div className="card p-6">
        <h3 className="font-bold mb-3">Projekt</h3>
        <p><strong>Arbeitstitel:</strong> {bundle.book.workingTitle}</p>
        <p><strong>Finaler Titel:</strong> {bundle.book.finalTitle}</p>
        <p><strong>Reihe:</strong> {bundle.book.seriesName} {bundle.book.seriesNumber}</p>
        <p><strong>Format:</strong> {bundle.book.format}</p>
        <p><strong>Geplant:</strong> {bundle.book.plannedPublishDate || '-'}</p>
      </div>
      <div className="card p-6">
        <h3 className="font-bold mb-3">Timeline</h3>
        <div className="space-y-2 text-sm">
          {bundle.events.slice(0, 10).map(e => (
            <div key={e.id} className="border-b pb-2">
              <span className="text-gray-500">{new Date(e.createdAt).toLocaleString('de-DE')}</span><br />
              {e.message}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Manuscripts({ bookId, items, onChange }) {
  const [file, setFile] = useState(null);
  const [versionLabel, setVersionLabel] = useState('');
  const [notes, setNotes] = useState('');

  async function upload() {
    if (!file) return alert('Bitte Datei auswählen.');
    await api.upload(`/api/books/${bookId}/upload/manuscript`, file, { versionLabel, notes, status: 'Entwurf' });
    setFile(null); setVersionLabel(''); setNotes('');
    onChange();
  }

  return (
    <div className="space-y-4">
      <div className="card p-6">
        <h3 className="font-bold mb-4">Manuskript-Version hochladen</h3>
        <div className="grid md:grid-cols-3 gap-4">
          <input type="file" onChange={e => setFile(e.target.files[0] || null)} className="border rounded p-2" />
          <Input label="Version" value={versionLabel} onChange={setVersionLabel} placeholder="z. B. v0.3" />
          <Input label="Notiz" value={notes} onChange={setNotes} placeholder="Was wurde geändert?" />
        </div>
        <button onClick={upload} className="aok-green text-white px-4 py-2 rounded mt-4">Hochladen</button>
      </div>

      <FileTable items={items} />
    </div>
  );
}

function Assets({ bookId, items, onChange }) {
  const [file, setFile] = useState(null);
  const [category, setCategory] = useState('Cover');
  const [versionLabel, setVersionLabel] = useState('');
  const [notes, setNotes] = useState('');

  async function upload() {
    if (!file) return alert('Bitte Datei auswählen.');
    await api.upload(`/api/books/${bookId}/upload/asset`, file, { category, versionLabel, notes, status: 'Entwurf' });
    setFile(null); setCategory('Cover'); setVersionLabel(''); setNotes('');
    onChange();
  }

  return (
    <div className="space-y-4">
      <div className="card p-6">
        <h3 className="font-bold mb-4">Cover oder Unterlage hochladen</h3>
        <div className="grid md:grid-cols-4 gap-4">
          <input type="file" onChange={e => setFile(e.target.files[0] || null)} className="border rounded p-2" />
          <Select label="Kategorie" value={category} onChange={setCategory}
            options={['Cover','KDP','Impressum','Marketing','Recherche','Rechtliches','Sonstiges'].map(x => [x,x])} />
          <Input label="Version" value={versionLabel} onChange={setVersionLabel} />
          <Input label="Notiz" value={notes} onChange={setNotes} />
        </div>
        <button onClick={upload} className="aok-green text-white px-4 py-2 rounded mt-4">Hochladen</button>
      </div>

      <FileTable items={items} />
    </div>
  );
}

function FileTable({ items }) {
  return (
    <div className="card p-6 overflow-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="text-left border-b">
            <th className="py-2">Version</th>
            <th>Datei</th>
            <th>Status</th>
            <th>Notiz</th>
            <th>Wörter</th>
            <th>Download</th>
          </tr>
        </thead>
        <tbody>
          {items.map(i => (
            <tr key={i.id} className="border-b">
              <td className="py-2">{i.versionLabel}</td>
              <td>{i.originalName}</td>
              <td>{i.status}</td>
              <td>{i.notes}</td>
              <td>{i.wordCount || '-'}</td>
              <td><a href={i.path} target="_blank" className="aok-green-text underline">öffnen</a></td>
            </tr>
          ))}
        </tbody>
      </table>
      {items.length === 0 && <p className="text-gray-500">Noch keine Dateien.</p>}
    </div>
  );
}

function KdpMetadata({ bookId, kdp, onChange }) {
  const [form, setForm] = useState(kdp || {
    title: '', subtitle: '', authorName: '', description: '', keywords: '', categories: '',
    language: 'de', isbn: '', publisher: '', aiDisclosure: 'Nicht festgelegt',
    trimSize: '', paperType: '', inkType: '', bleed: '', territories: '', pricePlan: '', kdpSelect: ''
  });

  useEffect(() => {
    if (kdp) setForm(kdp);
  }, [kdp]);

  async function save() {
    await api.put(`/api/books/${bookId}/kdp`, form);
    onChange();
    alert('KDP-Metadaten gespeichert.');
  }

  return (
    <div className="card p-6 space-y-4">
      <h3 className="font-bold text-lg">KDP-Metadaten</h3>
      <div className="grid md:grid-cols-2 gap-4">
        <Input label="Titel" value={form.title} onChange={v => setForm({...form, title:v})} />
        <Input label="Untertitel" value={form.subtitle} onChange={v => setForm({...form, subtitle:v})} />
        <Input label="Autorname" value={form.authorName} onChange={v => setForm({...form, authorName:v})} />
        <Input label="ISBN" value={form.isbn} onChange={v => setForm({...form, isbn:v})} />
        <Input label="Publisher / Imprint" value={form.publisher} onChange={v => setForm({...form, publisher:v})} />
        <Select label="KI-Offenlegung" value={form.aiDisclosure} onChange={v => setForm({...form, aiDisclosure:v})}
          options={['Nicht festgelegt','Keine KI-Inhalte','KI-unterstützt','KI-generiert'].map(x => [x,x])} />
        <Input label="Keywords" value={form.keywords} onChange={v => setForm({...form, keywords:v})} />
        <Input label="Kategorien" value={form.categories} onChange={v => setForm({...form, categories:v})} />
        <Input label="Trim Size" value={form.trimSize} onChange={v => setForm({...form, trimSize:v})} />
        <Input label="Preisplan" value={form.pricePlan} onChange={v => setForm({...form, pricePlan:v})} />
      </div>
      <Textarea label="Beschreibung / Klappentext" value={form.description} onChange={v => setForm({...form, description:v})} />
      <button onClick={save} className="aok-green text-white px-4 py-2 rounded">Speichern</button>
    </div>
  );
}

function Sales({ bookId, items, onChange }) {
  const [form, setForm] = useState({
    saleDate: new Date().toISOString().slice(0,10),
    marketplace: 'Amazon.de',
    format: 'eBook',
    units: 1,
    royaltyAmount: 0,
    currency: 'EUR'
  });

  async function save() {
    await api.post(`/api/books/${bookId}/sales`, form);
    setForm({...form, units:1, royaltyAmount:0});
    onChange();
  }

  const total = items.reduce((sum, x) => sum + Number(x.royaltyAmount || 0), 0);

  return (
    <div className="space-y-4">
      <div className="card p-6">
        <h3 className="font-bold mb-4">Verkauf erfassen</h3>
        <div className="grid md:grid-cols-6 gap-4">
          <Input label="Datum" type="date" value={form.saleDate} onChange={v => setForm({...form, saleDate:v})} />
          <Input label="Marketplace" value={form.marketplace} onChange={v => setForm({...form, marketplace:v})} />
          <Input label="Format" value={form.format} onChange={v => setForm({...form, format:v})} />
          <Input label="Einheiten" type="number" value={form.units} onChange={v => setForm({...form, units:v})} />
          <Input label="Royalty" type="number" value={form.royaltyAmount} onChange={v => setForm({...form, royaltyAmount:v})} />
          <Input label="Währung" value={form.currency} onChange={v => setForm({...form, currency:v})} />
        </div>
        <button onClick={save} className="aok-green text-white px-4 py-2 rounded mt-4">Speichern</button>
      </div>

      <div className="card p-6">
        <h3 className="font-bold mb-4">Verkäufe · Summe: {total.toLocaleString('de-DE')} EUR</h3>
        <table className="w-full text-sm">
          <tbody>
            {items.map(s => (
              <tr key={s.id} className="border-b">
                <td className="py-2">{s.saleDate}</td>
                <td>{s.marketplace}</td>
                <td>{s.format}</td>
                <td>{s.units}</td>
                <td>{s.royaltyAmount} {s.currency}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Tasks({ items, onChange }) {
  async function toggle(t) {
    await api.put('/api/tasks/' + t.id, { done: !t.done });
    onChange();
  }

  return (
    <div className="card p-6">
      <h3 className="font-bold mb-4">Checkliste</h3>
      <div className="space-y-2">
        {items.map(t => (
          <label key={t.id} className="flex items-center gap-3 border-b pb-2">
            <input type="checkbox" checked={!!t.done} onChange={() => toggle(t)} />
            <span className={t.done ? 'line-through text-gray-500' : ''}>{t.title}</span>
          </label>
        ))}
      </div>
    </div>
  );
}

function ExportPackage({ bookId }) {
  const [result, setResult] = useState(null);

  async function create() {
    const r = await api.post(`/api/books/${bookId}/export-package`, {});
    setResult(r);
  }

  return (
    <div className="card p-6">
      <h3 className="font-bold mb-4">KDP-Exportpaket</h3>
      <p className="text-sm text-gray-600 mb-4">
        Erstellt eine strukturierte HTML- und JSON-Übersicht mit Buchdaten, KDP-Metadaten, Versionen, Unterlagen und Aufgaben.
      </p>
      <button onClick={create} className="aok-green text-white px-4 py-2 rounded">Exportpaket erstellen</button>
      {result && (
        <div className="mt-4 bg-green-50 border-l-4 border-green-600 p-4">
          <p className="font-bold">Export erstellt</p>
          <a className="underline aok-green-text block" href={result.htmlUrl} target="_blank">HTML-Übersicht öffnen</a>
          <a className="underline aok-green-text block" href={result.jsonUrl} target="_blank">JSON-Daten öffnen</a>
        </div>
      )}
    </div>
  );
}

function Accounts() {
  const [items, setItems] = useState([]);
  const [form, setForm] = useState({
    accountName: '',
    accountEmail: '',
    marketplace: 'Amazon KDP',
    legalAddressLabel: '',
    taxProfileStatus: 'unbekannt',
    paymentProfileStatus: 'unbekannt',
    imprintNotes: '',
    notes: ''
  });

  async function load() {
    setItems(await api.get('/api/kdp-accounts'));
  }

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

  async function save() {
    await api.post('/api/kdp-accounts', form);
    setForm({ accountName: '', accountEmail: '', marketplace: 'Amazon KDP', legalAddressLabel: '', taxProfileStatus: 'unbekannt', paymentProfileStatus: 'unbekannt', imprintNotes: '', notes: '' });
    load();
  }

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold">KDP-Account / rechtliche Checkliste</h2>

      <div className="bg-yellow-50 border-l-4 border-yellow-500 p-4 text-yellow-900">
        Speichere hier keine Passwörter und möglichst keine Bankdaten. Nutze das Modul als Checkliste und Verwaltungsnotiz.
      </div>

      <div className="card p-6">
        <h3 className="font-bold mb-4">Account-Datensatz anlegen</h3>
        <div className="grid md:grid-cols-2 gap-4">
          <Input label="Account-Name" value={form.accountName} onChange={v => setForm({...form, accountName:v})} />
          <Input label="Account-E-Mail" value={form.accountEmail} onChange={v => setForm({...form, accountEmail:v})} />
          <Input label="Marketplace" value={form.marketplace} onChange={v => setForm({...form, marketplace:v})} />
          <Input label="Ladungsfähige Adresse / Label" value={form.legalAddressLabel} onChange={v => setForm({...form, legalAddressLabel:v})} />
          <Select label="Steuerprofil" value={form.taxProfileStatus} onChange={v => setForm({...form, taxProfileStatus:v})}
            options={['unbekannt','offen','eingereicht','vollständig'].map(x => [x,x])} />
          <Select label="Zahlungsprofil" value={form.paymentProfileStatus} onChange={v => setForm({...form, paymentProfileStatus:v})}
            options={['unbekannt','offen','vollständig'].map(x => [x,x])} />
          <Textarea label="Impressum / rechtliche Notizen" value={form.imprintNotes} onChange={v => setForm({...form, imprintNotes:v})} />
          <Textarea label="Sonstige Notizen" value={form.notes} onChange={v => setForm({...form, notes:v})} />
        </div>
        <button onClick={save} className="aok-green text-white px-4 py-2 rounded mt-4">Speichern</button>
      </div>

      <div className="grid md:grid-cols-2 gap-4">
        {items.map(i => (
          <div key={i.id} className="card p-4">
            <h3 className="font-bold">{i.accountName}</h3>
            <p className="text-sm text-gray-600">{i.marketplace} · {i.accountEmail}</p>
            <p className="text-sm mt-2">Steuerprofil: {i.taxProfileStatus}</p>
            <p className="text-sm">Zahlungsprofil: {i.paymentProfileStatus}</p>
            <p className="text-sm mt-2">{i.legalAddressLabel}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

function Input({ label, value, onChange, type = 'text', placeholder = '' }) {
  return (
    <label className="block">
      <span className="text-sm font-semibold">{label}</span>
      <input
        type={type}
        value={value || ''}
        placeholder={placeholder}
        onChange={e => onChange(e.target.value)}
        className="border rounded px-3 py-2 w-full mt-1"
      />
    </label>
  );
}

function Textarea({ label, value, onChange }) {
  return (
    <label className="block">
      <span className="text-sm font-semibold">{label}</span>
      <textarea
        value={value || ''}
        onChange={e => onChange(e.target.value)}
        className="border rounded px-3 py-2 w-full mt-1 min-h-24"
      />
    </label>
  );
}

function Select({ label, value, onChange, options }) {
  return (
    <label className="block">
      <span className="text-sm font-semibold">{label}</span>
      <select value={value || ''} onChange={e => onChange(e.target.value)} className="border rounded px-3 py-2 w-full mt-1">
        {options.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
      </select>
    </label>
  );
}

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