// Archiv tab — folder-organized archive of all generated docs.
// Sidebar: folder structure by kind. Main: file list. Right: preview.

function DocsArchiv({ docs, setDocs, rentals, equipment, company, templates, go, initialDocId }) {
  const t = useTheme();
  const toast = useToast();
  const [folder, setFolder] = useState('alle');
  const [query, setQuery] = useState('');
  const [selId, setSelId] = useState(initialDocId || (docs[0] && docs[0].id));
  const [confirmDel, setConfirmDel] = useState(null);

  useEffect(() => { if (initialDocId) setSelId(initialDocId); }, [initialDocId]);

  const folders = useMemo(() => {
    const groups = {
      vertrag:      docs.filter((d) => d.kind === 'vertrag').length,
      rechnung:     docs.filter((d) => d.kind === 'rechnung').length,
      protokoll:    docs.filter((d) => d.kind === 'protokoll' || d.kind === 'rueckgabe').length,
      reservierung: docs.filter((d) => d.kind === 'reservierung' || d.kind === 'erinnerung' || d.kind === 'inserat').length,
      custom:       docs.filter((d) => !['vertrag','rechnung','protokoll','rueckgabe','reservierung','erinnerung','inserat'].includes(d.kind)).length,
    };
    return [
      { id: 'alle',        label: 'Alle Dokumente',    count: docs.length, icon: icons.folder, color: t.text },
      { id: 'vertrag',     label: 'Mietverträge',       count: groups.vertrag,     icon: icons.fileText, color: '#007AFF' },
      { id: 'rechnung',    label: 'Rechnungen',         count: groups.rechnung,    icon: icons.invoice,  color: '#34C759' },
      { id: 'protokoll',   label: 'Übergabeprotokolle', count: groups.protokoll,   icon: icons.doc,      color: '#AF52DE' },
      { id: 'schnelltext', label: 'Schnelltexte',       count: groups.reservierung,icon: icons.mail,     color: '#5856D6' },
      { id: 'custom',      label: 'Sonstiges',          count: groups.custom,      icon: icons.folder,   color: '#8E8E93' },
    ];
  }, [docs, t.text]);

  const folderMatch = (d) => {
    if (folder === 'alle') return true;
    if (folder === 'vertrag') return d.kind === 'vertrag';
    if (folder === 'rechnung') return d.kind === 'rechnung';
    if (folder === 'protokoll') return d.kind === 'protokoll' || d.kind === 'rueckgabe';
    if (folder === 'schnelltext') return ['reservierung','erinnerung','inserat'].includes(d.kind);
    if (folder === 'custom') return !['vertrag','rechnung','protokoll','rueckgabe','reservierung','erinnerung','inserat'].includes(d.kind);
    return false;
  };

  const list = useMemo(() => {
    const filtered = docs.filter(folderMatch).filter((d) => {
      if (!query) return true;
      const r = rentals.find((x) => x.id === d.rentalId);
      return (d.title + ' ' + (r ? r.tenantName : '')).toLowerCase().includes(query.toLowerCase());
    });
    return filtered.sort((a, b) => (b.createdISO || '').localeCompare(a.createdISO || ''));
  }, [docs, folder, query, rentals]);

  const sel = docs.find((d) => d.id === selId) || list[0];
  const selRental = sel && rentals.find((r) => r.id === sel.rentalId);
  const selEq = selRental && equipment.find((e) => e.id === selRental.equipmentId);

  const del = (d) => {
    setDocs((prev) => prev.filter((x) => x.id !== d.id));
    if (selId === d.id) setSelId(null);
    setConfirmDel(null);
    toast('Dokument entfernt');
  };

  const copyText = (d) => {
    if (!d.body) return;
    try { navigator.clipboard.writeText(d.body); toast('Text kopiert'); } catch (e) { toast('Kopieren fehlgeschlagen'); }
  };

  // Format-of-file label
  const fileBadge = (d) => d.format === 'text' ? 'TXT' : 'PDF';

  return (
    <div style={{ flex: 1, display: 'flex', minHeight: 0, minWidth: 0 }}>
      {/* ── Folder sidebar ── */}
      <div style={{ width: 240, flexShrink: 0, borderRight: `0.5px solid ${t.sep}`, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div style={{ padding: '14px 16px 6px', fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>Ordner</div>
        <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding: '4px 10px 12px', display: 'flex', flexDirection: 'column', gap: 2 }}>
          {folders.map((f) => {
            const s = folder === f.id;
            return (
              <Pressable key={f.id} onClick={() => setFolder(f.id)} scale={0.99} hoverBg={s ? undefined : t.cardAlt}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 9, background: s ? t.chip : 'transparent', border: s ? `1px solid ${t.sep}` : '1px solid transparent' }}>
                  <div style={{ width: 26, height: 26, borderRadius: 7, background: f.color + '1c', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon d={f.icon} color={f.color} size={13} sw={1.8}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: s ? 600 : 500, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.label}</div>
                  <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, ...NUMS }}>{f.count}</div>
                </div>
              </Pressable>
            );
          })}
        </div>
      </div>

      {/* ── File list ── */}
      <div style={{ width: 360, flexShrink: 0, borderRight: `0.5px solid ${t.sep}`, display: 'flex', flexDirection: 'column', minHeight: 0, background: t.cardAlt }}>
        <div style={{ padding: '12px 14px', borderBottom: `0.5px solid ${t.sep}` }}>
          <SearchField value={query} onChange={setQuery} placeholder="Titel oder Mieter…"/>
        </div>
        <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding: 8 }}>
          {list.length === 0 && <div style={{ padding: '40px 20px', textAlign: 'center', color: t.textSec, fontSize: 13 }}>Keine Dokumente.</div>}
          {list.map((d) => {
            const r = rentals.find((x) => x.id === d.rentalId);
            const km = docKindMeta(d.kind);
            const s = sel && sel.id === d.id;
            return (
              <Pressable key={d.id} onClick={() => setSelId(d.id)} scale={0.997} hoverBg={s ? undefined : t.card}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '10px 12px', borderRadius: 10, background: s ? t.card : 'transparent', border: s ? `1px solid ${t.sep}` : '1px solid transparent', marginBottom: 2 }}>
                  <div style={{ width: 36, height: 44, borderRadius: 6, background: km.color + '1e', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexShrink: 0, position: 'relative' }}>
                    <Icon d={icons[km.icon] || icons.fileText} color={km.color} size={17} sw={1.7}/>
                    <div style={{ fontSize: 8.5, color: km.color, fontWeight: 800, marginTop: 1, letterSpacing: 0.3 }}>{fileBadge(d)}</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.title}</div>
                    <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r ? r.tenantName : '—'}{r ? ' · ' + fmtRange(r.start, r.end) : ''}</div>
                  </div>
                  <div style={{ fontSize: 10.5, color: t.textSec, fontWeight: 500, flexShrink: 0, ...NUMS }}>{d.createdISO ? fmtDateDE(d.createdISO) : ''}</div>
                </div>
              </Pressable>
            );
          })}
        </div>
      </div>

      {/* ── Preview ── */}
      <div className="rf-scroll" style={{ flex: 1, minWidth: 0, overflow: 'auto', background: t.dark ? '#0e0e10' : '#E8E8ED' }}>
        {sel ? (
          <div style={{ padding: '20px 28px 40px', display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
            {/* Header with actions */}
            <div style={{ width: '100%', maxWidth: 760, display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
              <div style={{ flex: '1 1 320px', minWidth: 0 }}>
                <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>{docKindMeta(sel.kind).label}</div>
                <div style={{ fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: -0.5, marginTop: 3 }}>{sel.title}</div>
                <div style={{ fontSize: 12.5, color: t.textSec, marginTop: 4 }}>
                  {selRental ? <>Für <Pressable onClick={() => go('rentals', { rentalId: selRental.id })} scale={0.98} style={{ display: 'inline-block' }}><span style={{ color: t.accent, fontWeight: 600, cursor: 'pointer' }}>{selRental.tenantName}</span></Pressable> · {fmtRange(selRental.start, selRental.end)}</> : '— ohne Mietvorgang —'}
                  {sel.createdISO ? ' · erstellt ' + fmtDateDE(sel.createdISO) : ''}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
                {sel.format === 'text' && <Button variant="primary" size="sm" icon={icons.download} onClick={() => copyText(sel)}>Kopieren</Button>}
                {sel.format === 'pdf' && <Button variant="primary" size="sm" icon={icons.download} onClick={() => toast('PDF exportiert')}>Als PDF</Button>}
                <Button variant="soft" size="sm" icon={icons.print} onClick={() => toast('Druckdialog geöffnet')}>Drucken</Button>
                <IconBtn icon={icons.trash} color={t.red} onClick={() => setConfirmDel(sel)} title="Löschen"/>
              </div>
            </div>

            {/* Body */}
            {sel.format === 'text' && (() => {
              // Fall back to the quick-text template body if the doc has none yet.
              let body = sel.body;
              if (!body) {
                const tpl = (typeof QUICK_TEXT_TEMPLATES !== 'undefined' ? QUICK_TEXT_TEMPLATES : []).find((x) => x.id === sel.templateId) ||
                            (typeof QUICK_TEXT_TEMPLATES !== 'undefined' ? QUICK_TEXT_TEMPLATES : []).find((x) => x.kind === sel.kind);
                if (tpl) body = selRental ? fillQuickText(tpl.body, selRental, selEq, company) : tpl.body;
              }
              return (
                <div style={{ width: '100%', maxWidth: 640, background: t.card, color: t.text, borderRadius: 14, border: `0.5px solid ${t.sep}`, boxShadow: t.shadowCard, padding: '22px 24px', fontSize: 14, lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>{body || <span style={{ color: t.textTer, fontStyle: 'italic' }}>Kein Inhalt hinterlegt.</span>}</div>
              );
            })()}
            {sel.format === 'pdf' && selRental && (() => {
              const tpl = templates.find((x) => x.id === sel.templateId) || templates.find((x) => x.kind === sel.kind) || templates[0];
              if (!tpl) return <div style={{ color: t.textSec }}>Keine Vorlage gefunden.</div>;
              return <DocPaper tpl={tpl} rental={selRental} eq={selEq} company={company}/>;
            })()}
          </div>
        ) : (
          <Empty icon={icons.archive} title="Kein Dokument gewählt" sub="Wähle links ein Dokument oder erstelle ein neues im Vorlagen-Tab."/>
        )}
      </div>

      <Confirm open={!!confirmDel} title="Dokument löschen?"
        message={confirmDel ? `„${confirmDel.title}" wird aus dem Archiv entfernt.` : ''}
        onConfirm={() => del(confirmDel)} onClose={() => setConfirmDel(null)}/>
    </div>
  );
}

Object.assign(window, { DocsArchiv });
