// Desktop Dokumente — three tabs:
//   • Vorlagen     — printable PDF templates (Mietvertrag/Rechnung/Übergabeprotokoll), letterhead preview
//   • Schnelltexte — WhatsApp/Kleinanzeigen text templates with copy-to-clipboard
//   • Archiv       — folder-organized archive of all generated docs, linked to rentals
//
// All generated documents are stored in the `docs` array (app-level state) and
// shown on the corresponding Mietvorgang detail pane.

const DEFAULT_TEMPLATES = [
  { id: 'vertrag', name: 'Mietvertrag', kind: 'vertrag', icon: 'fileText', color: '#007AFF', builtIn: true,
    title: 'Mietvertrag',
    fields: {
      mietgegenstand: 'Vermietet wird {{equipment}}{{zubehoer_satz}} Verwendungszweck: {{zweck}}.',
      mietdauer: 'Vom {{start}} ({{startzeit}} Uhr, Abholung) bis {{ende}} ({{endezeit}} Uhr, Rückgabe) — {{tage}}.',
      pflichten: 'Der Mieter verpflichtet sich, den Mietgegenstand pfleglich zu behandeln und in ordnungsgemäßem Zustand zurückzugeben. Schäden sind unverzüglich zu melden.',
    },
  },
  { id: 'rechnung', name: 'Rechnung', kind: 'rechnung', icon: 'invoice', color: '#34C759', builtIn: true,
    title: 'Rechnung',
    fields: {
      zahlungshinweis: 'Zahlbar innerhalb 14 Tagen ohne Abzug auf folgendes Konto:\n{{iban}} · Verwendungszweck: {{rechnungsnr}}',
    },
  },
  { id: 'protokoll', name: 'Übergabeprotokoll', kind: 'protokoll', icon: 'doc', color: '#AF52DE', builtIn: true,
    title: 'Übergabeprotokoll',
    fields: {
      zustandsoptionen: 'Einwandfrei | Gebrauchsspuren | Mängel (s. Notiz)',
    },
  },
];

const TOKENS_LIST = [
  ['mieter', 'Name des Mieters'], ['adresse', 'Anschrift'], ['telefon', 'Telefon'], ['email', 'E-Mail'], ['ausweis', 'Ausweis-Nr.'],
  ['equipment', 'Equipment-Name'], ['zubehoer', 'Zubehör (kommagetrennt)'], ['zweck', 'Verwendungszweck'],
  ['start', 'Startdatum'], ['ende', 'Enddatum'], ['startzeit', 'Abholzeit'], ['endezeit', 'Rückgabezeit'], ['tage', 'Mietdauer (Tage)'],
  ['summe', 'Mietsumme'], ['tagespreis', 'Tagespreis'], ['kaution', 'Kaution'],
  ['firma', 'Firma'], ['iban', 'IBAN'], ['datum', 'Heutiges Datum'],
  ['rechnungsnr', 'Rechnungsnummer'], ['vertragsnr', 'Vertragsnummer'],
];

function buildTokens(r, eq, company) {
  const days = daysBetween(r.start, r.end);
  return {
    mieter: r.tenantName, adresse: r.address || '—', telefon: r.phone || '—', email: r.email || '—', ausweis: r.idCard || '—',
    equipment: eq ? eq.name : r.equipmentName,
    zubehoer: eq && eq.accessories && eq.accessories.length ? eq.accessories.join(', ') : '',
    zubehoer_satz: eq && eq.accessories && eq.accessories.length ? ` inkl. Zubehör: ${eq.accessories.join(', ')}.` : '.',
    zweck: r.purpose || 'allgemeine Nutzung',
    start: fmtDateDE(r.start), ende: fmtDateDE(r.end),
    startzeit: r.startTime || '—', endezeit: r.endTime || '—',
    tage: days + ' Tag' + (days > 1 ? 'e' : ''),
    summe: rentalTotal(r) + ' €', tagespreis: r.dailyRate + ' €', kaution: r.deposit + ' €',
    firma: company.name, iban: company.iban, datum: fmtDateDE(todayISO()),
    rechnungsnr: 'RE-2026-' + r.id.replace(/\D/g, '').padStart(3, '0'),
    vertragsnr: 'MV-2026-' + r.id.replace(/\D/g, '').padStart(3, '0'),
  };
}
const sub = (txt, tok) => (txt || '').replace(/\{\{(\w+)\}\}/g, (_, k) => tok[k] !== undefined ? tok[k] : `{{${k}}}`);

// ── Top-level screen with left-side tabs ──
function ScreenDocuments({ go, nav, rentals, equipment, company, docs, setDocs }) {
  const t = useTheme();
  const [tab, setTab] = useState((nav && nav.docsTab) || 'vorlagen');
  const [initialRentalId, setInitialRentalId] = useState(null);
  const [initialDocId, setInitialDocId] = useState(null);
  const [templates, setTemplates] = useLocal('rf.docTemplates.v1', DEFAULT_TEMPLATES);

  useEffect(() => {
    if (!nav) return;
    if (nav.docsTab) setTab(nav.docsTab);
    if (nav.rentalId) setInitialRentalId(nav.rentalId);
    if (nav.docId) setInitialDocId(nav.docId);
  }, [nav]);

  const TABS = [
    { id: 'vorlagen',     label: 'Vorlagen',     sub: 'Verträge · Rechnungen',  icon: icons.fileText, color: '#007AFF' },
    { id: 'schnelltexte', label: 'Schnelltexte', sub: 'WhatsApp · Inserate',    icon: icons.mail,     color: '#34C759' },
    { id: 'archiv',       label: 'Archiv',       sub: `${docs.length} Dokumente`, icon: icons.archive,  color: '#AF52DE' },
  ];

  return (
    <>
      <Toolbar title="Dokumente" subtitle={TABS.find((x) => x.id === tab).sub}>
        <Segmented
          value={tab}
          onChange={setTab}
          options={TABS.map((x) => [x.id, x.label, x.id === 'archiv' ? docs.length : null])}
        />
      </Toolbar>
      <div style={{ flex: 1, display: 'flex', minHeight: 0, minWidth: 0 }}>
        {/* Active tab content */}
        {tab === 'vorlagen' && <DocsVorlagen rentals={rentals} equipment={equipment} company={company} templates={templates} setTemplates={setTemplates} docs={docs} setDocs={setDocs} initialRentalId={initialRentalId}/>}
        {tab === 'schnelltexte' && <DocsSchnelltexte rentals={rentals} equipment={equipment} company={company} docs={docs} setDocs={setDocs} initialRentalId={initialRentalId}/>}
        {tab === 'archiv' && <DocsArchiv docs={docs} setDocs={setDocs} rentals={rentals} equipment={equipment} company={company} templates={templates} go={go} initialDocId={initialDocId}/>}
      </div>
    </>
  );
}

// ── Vorlagen tab — generate printable PDFs ──
function DocsVorlagen({ rentals, equipment, company, templates, setTemplates, docs, setDocs, initialRentalId }) {
  const t = useTheme();
  const toast = useToast();
  const [selRental, setSelRental] = useState(initialRentalId || (rentals[0] ? rentals[0].id : null));
  const [selTpl, setSelTpl] = useState(templates[0] ? templates[0].id : null);
  const [editing, setEditing] = useState(false);
  const [confirmDel, setConfirmDel] = useState(null);
  const [zoom, setZoom] = useState(1);
  const [rentalMenu, setRentalMenu] = useState(false);
  const fileRef = useRef(null);
  const scrollRef = useRef(null);
  const rentalBtnRef = useRef(null);

  useEffect(() => { if (initialRentalId) setSelRental(initialRentalId); }, [initialRentalId]);

  const r = rentals.find((x) => x.id === selRental);
  const eq = r && equipment.find((e) => e.id === r.equipmentId);
  const tpl = templates.find((x) => x.id === selTpl) || templates[0];

  // Mousewheel zoom on the preview pane — centered around the cursor
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onWheel = (e) => {
      // Cmd/Ctrl + wheel = zoom. Plain wheel scrolls normally.
      if (!(e.metaKey || e.ctrlKey)) return;
      e.preventDefault();
      const delta = -e.deltaY * 0.0018;
      setZoom((z) => {
        const next = Math.max(0.4, Math.min(2.5, z + delta));
        return Math.round(next * 100) / 100;
      });
    };
    el.addEventListener('wheel', onWheel, { passive: false });
    return () => el.removeEventListener('wheel', onWheel);
  }, []);

  // Close rental dropdown when clicking outside
  useEffect(() => {
    if (!rentalMenu) return;
    const close = (e) => {
      if (rentalBtnRef.current && !rentalBtnRef.current.contains(e.target)) setRentalMenu(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [rentalMenu]);

  const patchTpl = (patch) => setTemplates((prev) => prev.map((x) => x.id === tpl.id ? { ...x, ...patch } : x));
  const patchField = (k, v) => patchTpl({ fields: { ...tpl.fields, [k]: v } });
  const resetTpl = () => {
    const def = DEFAULT_TEMPLATES.find((d) => d.id === tpl.id);
    if (def) { setTemplates((prev) => prev.map((x) => x.id === tpl.id ? def : x)); toast('Vorlage zurückgesetzt'); }
  };
  const deleteTpl = (id) => {
    setTemplates((prev) => prev.filter((x) => x.id !== id));
    if (selTpl === id) setSelTpl(templates[0] ? templates[0].id : null);
    toast('Vorlage gelöscht');
  };
  const onUpload = (e) => {
    const file = e.target.files && e.target.files[0]; if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      const isText = /\.(txt|md|html?)$/i.test(file.name);
      const body = isText ? String(reader.result) :
        `Sehr geehrte/r {{mieter}},\n\nhiermit bestätigen wir die Vermietung von {{equipment}} im Zeitraum {{start}} – {{ende}}.\n\nMietsumme: {{summe}}\nKaution: {{kaution}}\n\nMit freundlichen Grüßen\n{{firma}}`;
      const id = 'tpl-' + Date.now();
      const name = file.name.replace(/\.[^.]+$/, '');
      setTemplates((prev) => [...prev, {
        id, name, kind: 'custom', icon: 'fileText', color: '#FF9500', builtIn: false,
        title: name, fileName: file.name,
        fields: { body },
      }]);
      setSelTpl(id); setEditing(true);
      toast(`„${file.name}" als Vorlage importiert`);
    };
    if (/\.(txt|md|html?)$/i.test(file.name)) reader.readAsText(file); else reader.readAsArrayBuffer(file);
    e.target.value = '';
  };

  const saveToArchive = () => {
    if (!r || !tpl) return;
    const tok = buildTokens(r, eq, company);
    const number = tpl.kind === 'rechnung' ? tok.rechnungsnr : tpl.kind === 'vertrag' ? tok.vertragsnr : null;
    const doc = {
      id: 'd-' + Date.now(),
      kind: tpl.kind,
      format: 'pdf',
      title: number ? `${tpl.name} ${number}` : `${tpl.name} · ${r.tenantName}`,
      rentalId: r.id,
      templateId: tpl.id,
      number,
      createdISO: todayISO(),
    };
    setDocs((prev) => [doc, ...prev]);
    toast('Im Archiv gespeichert');
  };

  const standardTpls = templates.filter((x) => x.builtIn);
  const customTpls = templates.filter((x) => !x.builtIn);

  const renderTplRow = (d) => {
    const sel = selTpl === d.id;
    return (
      <Pressable key={d.id} onClick={() => setSelTpl(d.id)} scale={0.99} hoverBg={sel ? undefined : t.cardAlt}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 10px', borderRadius: 10, background: sel ? t.chip : 'transparent', border: sel ? `1px solid ${t.sep}` : '1px solid transparent' }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: d.color + '22', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon d={icons[d.icon] || icons.fileText} color={d.color} size={15} sw={1.9}/></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</div>
            <div style={{ fontSize: 10.5, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.builtIn ? 'Standard-Vorlage' : (d.fileName || 'Eigene Vorlage')}</div>
          </div>
          {!d.builtIn && (
            <Pressable onClick={(e) => { e.stopPropagation(); setConfirmDel(d); }} scale={0.9}>
              <div title="Löschen" style={{ width: 22, height: 22, borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: 0.55 }}><Icon d={icons.trash} color={t.textSec} size={13} sw={1.8}/></div>
            </Pressable>
          )}
        </div>
      </Pressable>
    );
  };

  const zoomPct = Math.round(zoom * 100);
  const zoomBtn = (label, onClick, disabled) => (
    <Pressable onClick={disabled ? undefined : onClick} scale={0.92}>
      <div style={{ width: 26, height: 26, borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 600, color: disabled ? t.textSec : t.text, opacity: disabled ? 0.4 : 1, userSelect: 'none' }}>{label}</div>
    </Pressable>
  );

  return (
    <div style={{ flex: 1, display: 'flex', minHeight: 0, minWidth: 0 }}>
      {/* ── Sidebar: templates ── */}
      <div style={{ width: 264, flexShrink: 0, borderRight: `0.5px solid ${t.sep}`, display: 'flex', flexDirection: 'column', minHeight: 0, background: t.cardAlt }}>
        <div style={{ padding: '14px 16px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>Vorlagen</div>
          <Pressable onClick={() => fileRef.current && fileRef.current.click()} scale={0.94}>
            <div title="Eigene Vorlage hochladen" style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '4px 8px', borderRadius: 7, background: t.chip, fontSize: 11, fontWeight: 600, color: t.text }}>
              <Icon d={icons.upload} color={t.text} size={11} sw={2.2}/>Hochladen
            </div>
          </Pressable>
          <input ref={fileRef} type="file" accept=".txt,.md,.html,.htm,.doc,.docx,.pdf" style={{ display: 'none' }} onChange={onUpload}/>
        </div>
        <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding: '0 12px 12px', display: 'flex', flexDirection: 'column', gap: 2 }}>
          <div style={{ fontSize: 10, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, padding: '8px 6px 4px' }}>Standard</div>
          {standardTpls.map(renderTplRow)}
          {customTpls.length > 0 && (
            <>
              <div style={{ fontSize: 10, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, padding: '12px 6px 4px' }}>Eigene</div>
              {customTpls.map(renderTplRow)}
            </>
          )}
        </div>
      </div>

      {/* ── Editor (when bearbeiten is on) ── */}
      {editing && tpl && (
        <TemplateEditor t={t} tpl={tpl} onPatchTpl={patchTpl} onPatchField={patchField} onReset={resetTpl} onDelete={() => setConfirmDel(tpl)}/>
      )}

      {/* ── Preview pane ── */}
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', background: t.dark ? '#0e0e10' : '#E8E8ED' }}>
        {/* Action bar */}
        {r && tpl && (
          <div style={{ position: 'relative', zIndex: 10, flexShrink: 0, background: t.dark ? 'rgba(20,20,22,0.85)' : 'rgba(248,248,250,0.85)', backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)', borderBottom: `0.5px solid ${t.sep}`, padding: '10px 20px', display: 'flex', alignItems: 'center', gap: 10 }}>
            {/* Mietvorgang dropdown */}
            <div ref={rentalBtnRef} style={{ position: 'relative' }}>
              <Pressable onClick={() => setRentalMenu((v) => !v)} scale={0.98}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '5px 10px 5px 6px', borderRadius: 9, background: t.card, border: `1px solid ${t.sep}`, boxShadow: '0 1px 2px rgba(0,0,0,0.04)', minWidth: 240 }}>
                  <Avatar name={r.tenantName} size={28}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.tenantName}</div>
                    <div style={{ fontSize: 10.5, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{eq ? eq.name : r.equipmentName}</div>
                  </div>
                  <Icon d={icons.chevronDown || 'M6 9l6 6 6-6'} color={t.textSec} size={14} sw={2}/>
                </div>
              </Pressable>
              {rentalMenu && (
                <div className="rf-scroll" style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, width: 320, maxHeight: 380, overflow: 'auto', background: t.card, borderRadius: 11, border: `1px solid ${t.sep}`, boxShadow: '0 12px 40px rgba(0,0,0,0.18)', padding: 6, zIndex: 50 }}>
                  {rentals.map((x) => {
                    const e = equipment.find((q) => q.id === x.equipmentId);
                    const sel = x.id === selRental;
                    return (
                      <Pressable key={x.id} onClick={() => { setSelRental(x.id); setRentalMenu(false); }} scale={0.99} hoverBg={sel ? undefined : t.cardAlt}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 8, background: sel ? t.chip : 'transparent' }}>
                          <Avatar name={x.tenantName} size={28}/>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontSize: 12.5, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{x.tenantName}</div>
                            <div style={{ fontSize: 10.5, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e ? e.name : x.equipmentName}</div>
                          </div>
                          <StatusPill status={x.status}/>
                        </div>
                      </Pressable>
                    );
                  })}
                </div>
              )}
            </div>

            <div style={{ flex: 1 }}/>

            {/* Zoom controls */}
            <div title="⌘ + Mausrad zum Zoomen" style={{ display: 'flex', alignItems: 'center', gap: 0, padding: 2, borderRadius: 8, background: t.card, border: `1px solid ${t.sep}` }}>
              {zoomBtn('−', () => setZoom((z) => Math.max(0.4, Math.round((z - 0.1) * 100) / 100)), zoom <= 0.4)}
              <Pressable onClick={() => setZoom(1)} scale={0.96}>
                <div style={{ minWidth: 48, textAlign: 'center', fontSize: 11.5, fontWeight: 600, color: t.text, fontVariantNumeric: 'tabular-nums', padding: '0 4px', userSelect: 'none' }}>{zoomPct}%</div>
              </Pressable>
              {zoomBtn('+', () => setZoom((z) => Math.min(2.5, Math.round((z + 0.1) * 100) / 100)), zoom >= 2.5)}
            </div>

            <div style={{ width: 1, height: 22, background: t.sep, margin: '0 4px' }}/>

            <Button variant={editing ? 'accent' : 'soft'} size="sm" icon={editing ? icons.check : icons.edit} onClick={() => setEditing((v) => !v)}>{editing ? 'Fertig' : 'Bearbeiten'}</Button>
            {!editing && <Button variant="soft" size="sm" icon={icons.print} onClick={() => toast('Druckdialog geöffnet')}>Drucken</Button>}
            {!editing && <Button variant="soft" size="sm" icon={icons.archive} onClick={saveToArchive}>Archiv</Button>}
            {!editing && <Button variant="primary" size="sm" icon={icons.download} onClick={() => { saveToArchive(); toast('PDF exportiert'); }}>Als PDF</Button>}
          </div>
        )}

        {/* Scrollable paper area */}
        <div ref={scrollRef} className="rf-scroll" style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>
          <div style={{ minWidth: 'max-content', minHeight: '100%', padding: 36, display: 'flex', justifyContent: 'center', alignItems: 'flex-start' }}>
            {r && tpl ? (
              <div style={{ transform: `scale(${zoom})`, transformOrigin: 'top center', transition: 'transform 0.08s ease-out' }}>
                <DocPaper tpl={tpl} rental={r} eq={eq} company={company}/>
              </div>
            ) : <Empty icon={icons.doc} title="Kein Mietvorgang gewählt"/>}
          </div>
        </div>
      </div>

      <Confirm open={!!confirmDel} title="Vorlage löschen?"
        message={confirmDel ? (confirmDel.builtIn ? `„${confirmDel.name}" wird auf die Standard-Vorlage zurückgesetzt.` : `„${confirmDel.name}" wird unwiderruflich entfernt.`) : ''}
        onConfirm={() => { if (confirmDel.builtIn) resetTpl(); else deleteTpl(confirmDel.id); }}
        onClose={() => setConfirmDel(null)}/>
    </div>
  );
}

// ── Template editor (left panel when "Bearbeiten" is on) ──
function TemplateEditor({ t, tpl, onPatchTpl, onPatchField, onReset, onDelete }) {
  const fieldDefs = tpl.kind === 'vertrag' ? [
    { key: 'mietgegenstand', label: '§1 Mietgegenstand', rows: 3 },
    { key: 'mietdauer',      label: '§2 Mietdauer',      rows: 2 },
    { key: 'pflichten',      label: '§4 Pflichten des Mieters', rows: 4 },
  ] : tpl.kind === 'rechnung' ? [
    { key: 'zahlungshinweis', label: 'Zahlungshinweis (Fußzeile)', rows: 3 },
  ] : tpl.kind === 'protokoll' ? [
    { key: 'zustandsoptionen', label: 'Zustands-Optionen (mit | getrennt)', rows: 2 },
  ] : [
    { key: 'body', label: 'Dokument-Inhalt', rows: 16 },
  ];

  const ta = {
    width: '100%', fontFamily: 'inherit', fontSize: 13, lineHeight: 1.55,
    padding: '10px 12px', border: `1px solid ${t.sep}`, borderRadius: 9,
    background: t.inputBg, color: t.text, resize: 'vertical', outline: 'none',
    boxSizing: 'border-box',
  };

  return (
    <div style={{ width: 380, flexShrink: 0, borderRight: `0.5px solid ${t.sep}`, display: 'flex', flexDirection: 'column', minHeight: 0, background: t.card }}>
      <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding: '18px 18px 24px' }}>
        <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Vorlage bearbeiten</div>
        <input value={tpl.name} onChange={(e) => onPatchTpl({ name: e.target.value, title: e.target.value })}
          style={{ width: '100%', fontSize: 19, fontWeight: 700, color: t.text, background: 'transparent', border: 'none', outline: 'none', padding: '2px 0', letterSpacing: -0.3, boxSizing: 'border-box' }}/>
        <div style={{ fontSize: 12, color: t.textSec, marginTop: 2, marginBottom: 16 }}>{tpl.builtIn ? 'Standard-Vorlage' : (tpl.fileName || 'Eigene Vorlage')}</div>

        {fieldDefs.map((f) => (
          <div key={f.key} style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>{f.label}</div>
            <textarea rows={f.rows} value={tpl.fields[f.key] || ''} onChange={(e) => onPatchField(f.key, e.target.value)} style={ta}/>
          </div>
        ))}

        <div style={{ marginTop: 18, padding: '12px 14px', borderRadius: 10, background: t.cardAlt, border: `0.5px solid ${t.sep}` }}>
          <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 8 }}>Verfügbare Platzhalter</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
            {TOKENS_LIST.map(([k, lab]) => (
              <span key={k} title={lab} style={{ fontSize: 11, fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace', padding: '3px 7px', borderRadius: 6, background: t.chip, color: t.text }}>{`{{${k}}}`}</span>
            ))}
          </div>
          <div style={{ fontSize: 11, color: t.textSec, marginTop: 8, lineHeight: 1.5 }}>Platzhalter werden beim Erstellen automatisch durch die Daten des gewählten Mietvorgangs ersetzt.</div>
        </div>

        <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
          {tpl.builtIn ? (
            <Button variant="soft" size="sm" icon={icons.refresh} onClick={onReset}>Zurücksetzen</Button>
          ) : (
            <Button variant="soft" size="sm" icon={icons.trash} onClick={onDelete}>Löschen</Button>
          )}
        </div>
      </div>
    </div>
  );
}

// A4-ish paper document
function DocPaper({ tpl, rental, eq, company }) {
  const r = rental;
  const days = daysBetween(r.start, r.end);
  const net = Math.round(rentalTotal(r) / 1.19);
  const vat = rentalTotal(r) - net;
  const ink = '#1a1a1a', soft = '#666', line = '#e0e0e0';
  const page = { width: 720, minHeight: 980, background: '#fff', color: ink, padding: '56px 60px', boxShadow: '0 12px 40px rgba(0,0,0,0.18)', borderRadius: 3, fontSize: 13, lineHeight: 1.6 };
  const H = ({ children }) => <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.5, marginBottom: 4 }}>{children}</div>;
  const Label = ({ children }) => <div style={{ fontSize: 10, color: soft, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 4 }}>{children}</div>;
  const tok = buildTokens(r, eq, company);
  const f = tpl.fields || {};

  const Letterhead = () => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, paddingBottom: 18, borderBottom: `2px solid ${ink}`, marginBottom: 24 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, minWidth: 0 }}>
        {company.logo && <img src={company.logo} alt="Logo" style={{ width: 56, height: 56, objectFit: 'contain', borderRadius: 6, flexShrink: 0 }}/>}
        <div>
          <div style={{ fontSize: 17, fontWeight: 800, letterSpacing: -0.3 }}>{company.name}</div>
          <div style={{ fontSize: 11, color: soft, marginTop: 3 }}>{company.street} · {company.city}</div>
        </div>
      </div>
      <div style={{ textAlign: 'right', fontSize: 11, color: soft, lineHeight: 1.7 }}>
        <div>{company.email}</div><div>{company.phone}</div><div>USt-IdNr. {company.ust}</div>
      </div>
    </div>
  );

  if (tpl.kind === 'vertrag') return (
    <div style={page}>
      <Letterhead/>
      <H>{tpl.title || 'Mietvertrag'}</H>
      <div style={{ fontSize: 12, color: soft, marginBottom: 24 }}>Vertrags-Nr. {tok.vertragsnr} · {tok.datum}</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 24 }}>
        <div><Label>Vermieter</Label><div style={{ fontWeight: 600 }}>{company.name}</div><div style={{ color: soft, whiteSpace: 'pre-line' }}>{company.owner}{'\n'}{company.street}{'\n'}{company.city}</div></div>
        <div><Label>Mieter</Label><div style={{ fontWeight: 600 }}>{r.tenantName}</div><div style={{ color: soft, whiteSpace: 'pre-line' }}>{r.address || '—'}{'\n'}{r.phone}{'\n'}Ausweis: {r.idCard || '—'}</div></div>
      </div>
      <Label>§1 Mietgegenstand</Label>
      <div style={{ marginBottom: 16, whiteSpace: 'pre-line' }}>{sub(f.mietgegenstand, tok)}</div>
      <Label>§2 Mietdauer</Label>
      <div style={{ marginBottom: 16, whiteSpace: 'pre-line' }}>{sub(f.mietdauer, tok)}</div>
      <Label>§3 Mietpreis & Kaution</Label>
      <div style={{ background: '#f6f6f8', borderRadius: 8, padding: '12px 16px', marginBottom: 16 }}>
        <Line k={`Tagespreis × ${days}${Number(r.quantity) > 1 ? ` × ${r.quantity}` : ''}`} v={`${rentalTotal(r)} €`} line={line}/>
        <Line k="Kaution (bei Rückgabe erstattet)" v={`${r.deposit} €`} line={line}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 15, paddingTop: 8 }}><span>Gesamt fällig</span><span>{rentalTotal(r) + r.deposit} €</span></div>
      </div>
      <Label>§4 Pflichten des Mieters</Label>
      <div style={{ marginBottom: 24, color: soft, whiteSpace: 'pre-line' }}>{sub(f.pflichten, tok)}</div>
      <div style={{ display: 'flex', gap: 40, marginTop: 56 }}>
        {['Ort, Datum · Vermieter', 'Ort, Datum · Mieter'].map((l) => <div key={l} style={{ flex: 1 }}><div style={{ borderTop: `1px solid ${ink}`, paddingTop: 6, fontSize: 11, color: soft }}>{l}</div></div>)}
      </div>
    </div>
  );

  if (tpl.kind === 'rechnung') return (
    <div style={page}>
      <Letterhead/>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div><H>{tpl.title || 'Rechnung'}</H><div style={{ fontSize: 12, color: soft }}>{tok.rechnungsnr}</div></div>
        <div style={{ textAlign: 'right', fontSize: 12, color: soft, lineHeight: 1.7 }}><div>Datum: {tok.datum}</div><div>Leistungszeitraum:</div><div style={{ color: ink, fontWeight: 600 }}>{fmtRange(r.start, r.end)}</div></div>
      </div>
      <div style={{ marginTop: 24, marginBottom: 24 }}><Label>Rechnung an</Label><div style={{ fontWeight: 600 }}>{r.tenantName}</div><div style={{ color: soft, whiteSpace: 'pre-line' }}>{r.address || '—'}</div></div>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
        <thead><tr style={{ borderBottom: `2px solid ${ink}` }}>
          {['Pos.', 'Beschreibung', 'Tage', 'Einzel', 'Summe'].map((h, i) => <th key={h} style={{ textAlign: i > 1 ? 'right' : 'left', padding: '8px 4px', fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.5, color: soft }}>{h}</th>)}
        </tr></thead>
        <tbody>
          <tr style={{ borderBottom: `1px solid ${line}` }}>
            <td style={{ padding: '12px 4px' }}>1</td>
            <td style={{ padding: '12px 4px' }}><div style={{ fontWeight: 600 }}>{eq ? eq.name : r.equipmentName}</div><div style={{ fontSize: 11, color: soft }}>{r.purpose || 'Vermietung'}</div></td>
            <td style={{ textAlign: 'right', padding: '12px 4px' }}>{days}</td>
            <td style={{ textAlign: 'right', padding: '12px 4px' }}>{r.dailyRate} €</td>
            <td style={{ textAlign: 'right', padding: '12px 4px', fontWeight: 600 }}>{rentalTotal(r)} €</td>
          </tr>
        </tbody>
      </table>
      <div style={{ marginLeft: 'auto', width: 260, marginTop: 16 }}>
        <Line k="Netto" v={`${net} €`} line={line}/>
        <Line k="zzgl. 19% USt." v={`${vat} €`} line={line}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 17, paddingTop: 8 }}><span>Gesamt</span><span>{rentalTotal(r)} €</span></div>
      </div>
      <div style={{ marginTop: 32, padding: '14px 16px', background: '#f6f6f8', borderRadius: 8, fontSize: 12, color: soft, whiteSpace: 'pre-line' }}>
        {sub(f.zahlungshinweis, tok)}
        <div style={{ marginTop: 8 }}>Status: <strong style={{ color: r.paymentStatus === 'bezahlt' ? '#34C759' : '#FF9500' }}>{r.paymentStatus === 'bezahlt' ? 'Bezahlt' : 'Offen'}</strong></div>
      </div>
    </div>
  );

  if (tpl.kind === 'protokoll') {
    const zustOpts = (f.zustandsoptionen || 'Einwandfrei | Gebrauchsspuren | Mängel (s. Notiz)').split('|').map((s) => s.trim()).filter(Boolean);
    return (
      <div style={page}>
        <Letterhead/>
        <H>{tpl.title || 'Übergabeprotokoll'}</H>
        <div style={{ fontSize: 12, color: soft, marginBottom: 24 }}>{eq ? eq.name : r.equipmentName} · {r.tenantName}</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 20 }}>
          <div><Label>Übergabe (Abholung)</Label><div style={{ fontWeight: 600 }}>{fmtDateDE(r.start)} · {r.startTime} Uhr</div></div>
          <div><Label>Rückgabe</Label><div style={{ fontWeight: 600 }}>{fmtDateDE(r.end)} · {r.endTime} Uhr</div></div>
        </div>
        <Label>Mitgeführtes Zubehör</Label>
        <div style={{ marginBottom: 20 }}>
          {(eq && eq.accessories && eq.accessories.length ? eq.accessories : ['Gerät', 'Stromkabel']).map((a, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 0', borderBottom: `1px solid ${line}` }}>
              <div style={{ width: 16, height: 16, border: `1.5px solid ${soft}`, borderRadius: 4 }}/><span>{a}</span>
            </div>
          ))}
        </div>
        <Label>Zustand bei Übergabe</Label>
        <div style={{ display: 'flex', gap: 16, marginBottom: 20, flexWrap: 'wrap' }}>{zustOpts.map((l) => <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 7 }}><div style={{ width: 15, height: 15, border: `1.5px solid ${soft}`, borderRadius: 4 }}/><span style={{ fontSize: 12 }}>{l}</span></div>)}</div>
        <Label>Notizen</Label>
        <div style={{ height: 70, border: `1px solid ${line}`, borderRadius: 8, marginBottom: 24 }}/>
        <div style={{ display: 'flex', gap: 40, marginTop: 40 }}>
          {['Unterschrift Vermieter', 'Unterschrift Mieter'].map((l) => <div key={l} style={{ flex: 1 }}><div style={{ borderTop: `1px solid ${ink}`, paddingTop: 6, fontSize: 11, color: soft }}>{l}</div></div>)}
        </div>
      </div>
    );
  }

  // custom user-uploaded template
  return (
    <div style={page}>
      <Letterhead/>
      <H>{tpl.title || tpl.name}</H>
      <div style={{ fontSize: 12, color: soft, marginBottom: 24 }}>{tok.datum} · {r.tenantName}</div>
      <div style={{ whiteSpace: 'pre-wrap', fontSize: 13, lineHeight: 1.7, color: ink }}>{sub(f.body, tok)}</div>
      <div style={{ display: 'flex', gap: 40, marginTop: 56 }}>
        {['Ort, Datum · Vermieter', 'Ort, Datum · Mieter'].map((l) => <div key={l} style={{ flex: 1 }}><div style={{ borderTop: `1px solid ${ink}`, paddingTop: 6, fontSize: 11, color: soft }}>{l}</div></div>)}
      </div>
    </div>
  );
}

function Line({ k, v, line }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0', borderBottom: `1px solid ${line}`, fontSize: 13 }}><span style={{ color: '#666' }}>{k}</span><span style={{ fontWeight: 600 }}>{v}</span></div>;
}

// ── Firmenprofil ──
// Tabs (left rail) → Sections (right pane). All edits go through `form` and
// commit to `company` via the "Speichern" button in the toolbar when dirty.
function ScreenProfile({ company, setCompany, dark, toggleDark, data }) {
  const t = useTheme();
  const toast = useToast();
  const merged = { ...DEFAULT_COMPANY, ...(company || {}) };
  const [form, setForm] = useState(merged);
  useEffect(() => setForm({ ...DEFAULT_COMPANY, ...(company || {}) }), [company]);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const setNum = (k, v, dflt = 0) => setForm((f) => ({ ...f, [k]: v === '' ? '' : (isNaN(Number(v)) ? dflt : Number(v)) }));
  const dirty = JSON.stringify(form) !== JSON.stringify(merged);
  const card = { background: t.card, borderRadius: 16, boxShadow: t.shadowCard, padding: 24 };
  const logoRef = useRef(null);

  // ── Datensicherung ── persistent last-backup metadata + import/reset confirm state ──
  const d = data || {};
  const [lastBackup, setLastBackup] = useLocal('rf-d-last-backup', null); // { dateISO, size, counts }
  const [confirmReset, setConfirmReset] = useState(false);
  const [pendingImport, setPendingImport] = useState(null); // { payload, name, size }
  const importRef = useRef(null);
  const onPickLogo = (e) => {
    const file = e.target.files && e.target.files[0]; if (!file) return;
    if (!/^image\//.test(file.type)) { toast('Bitte eine Bilddatei wählen'); e.target.value = ''; return; }
    const reader = new FileReader();
    reader.onload = () => { set('logo', String(reader.result)); toast('Logo aktualisiert – jetzt speichern'); };
    reader.readAsDataURL(file);
    e.target.value = '';
  };

  // Tab navigation
  const TABS = [
    { id: 'stammdaten',    label: 'Stammdaten',    icon: icons.building, sub: 'Firma & Kontakt' },
    { id: 'bank',          label: 'Bank & Steuer', icon: icons.euro,     sub: 'IBAN, USt, MwSt.' },
    { id: 'logistik',      label: 'Logistik',      icon: icons.truck,    sub: 'Lager & km-Sätze' },
    { id: 'dokumente',     label: 'Dokumente',     icon: icons.fileText, sub: 'Nummern & Fristen' },
    { id: 'erinnerungen',  label: 'Erinnerungen',  icon: icons.bell,     sub: 'Push & Vorlauf' },
    { id: 'datensicherung',label: 'Datensicherung',icon: icons.archive,  sub: 'Export & Import' },
    { id: 'darstellung',   label: 'Darstellung',   icon: icons.moon,     sub: 'Hell · Dunkel' }];

  const [tab, setTab] = useState('stammdaten');

  // Local Toggle (mirrors the rentals screen pattern)
  const Toggle = ({ on, onClick }) => (
    <Pressable onClick={onClick} scale={0.95}>
      <div style={{ width: 46, height: 28, borderRadius: 14, background: on ? t.green : t.chipStrong, position: 'relative', transition: 'background 0.15s' }}>
        <div style={{ position: 'absolute', top: 2, left: on ? 20 : 2, width: 24, height: 24, borderRadius: 12, background: '#fff', boxShadow: '0 2px 6px rgba(0,0,0,0.18)', transition: 'left 0.15s' }} />
      </div>
    </Pressable>
  );

  const Row = ({ title, sub, children, last }) => (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 18, padding: '14px 0', borderBottom: last ? 'none' : `0.5px solid ${t.sep}` }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{title}</div>
        {sub && <div style={{ fontSize: 12, color: t.textSec, marginTop: 2 }}>{sub}</div>}
      </div>
      <div style={{ flexShrink: 0 }}>{children}</div>
    </div>
  );

  const NumInput = ({ value, onChange, suffix, width = 110 }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <input value={value} onChange={onChange} style={{ width, padding: '8px 10px', borderRadius: 8, border: `0.5px solid ${t.inputBorder}`, background: t.inputBg, fontSize: 14, color: t.text, fontFamily: 'inherit', fontWeight: 600, textAlign: 'right', boxSizing: 'border-box', fontVariantNumeric: 'tabular-nums' }}/>
      {suffix && <span style={{ fontSize: 13, color: t.textSec, fontWeight: 500, minWidth: 28 }}>{suffix}</span>}
    </div>
  );

  // ── Sections ──────────────────────────────────────────────────────────
  const StammdatenSection = (
    <>
      <div style={card}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 18 }}>
          <Pressable onClick={() => logoRef.current && logoRef.current.click()} scale={0.96}>
            <div title="Logo hochladen" style={{ width: 72, height: 72, borderRadius: 16, background: form.logo ? t.card : t.accent, border: form.logo ? `1px solid ${t.sep}` : 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', position: 'relative' }}>
              {form.logo ? (
                <img src={form.logo} alt="Logo" style={{ maxWidth: '88%', maxHeight: '88%', objectFit: 'contain' }}/>
              ) : (
                <Icon d={icons.building} color="#fff" size={30} sw={1.8}/>
              )}
            </div>
          </Pressable>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: t.text }}>{form.name}</div>
            <div style={{ fontSize: 13, color: t.textSec }}>{form.owner}</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
              <Button variant="soft" size="sm" icon={icons.upload} onClick={() => logoRef.current && logoRef.current.click()}>{form.logo ? 'Logo ändern' : 'Logo hochladen'}</Button>
              {form.logo && <Button variant="soft" size="sm" icon={icons.trash} onClick={() => set('logo', '')}>Entfernen</Button>}
            </div>
            <input ref={logoRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={onPickLogo}/>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="Firmenname"><TextInput value={form.name} onChange={(e) => set('name', e.target.value)}/></Field>
          <Field label="Inhaber"><TextInput value={form.owner} onChange={(e) => set('owner', e.target.value)}/></Field>
          <Field label="Straße"><TextInput value={form.street} onChange={(e) => set('street', e.target.value)}/></Field>
          <Field label="PLZ & Ort"><TextInput value={form.city} onChange={(e) => set('city', e.target.value)}/></Field>
          <Field label="E-Mail"><TextInput value={form.email} onChange={(e) => set('email', e.target.value)}/></Field>
          <Field label="Telefon"><TextInput value={form.phone} onChange={(e) => set('phone', e.target.value)}/></Field>
          <Field label="Website" style={{ gridColumn: '1 / -1' }}><TextInput value={form.website || ''} onChange={(e) => set('website', e.target.value)} placeholder="www.example.de"/></Field>
        </div>
      </div>

      <div style={card}>
        <SectionTitle>Register & Steuer-IDs</SectionTitle>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 4 }}>
          <Field label="Steuernummer" hint="Vom Finanzamt vergeben"><TextInput value={form.taxNumber || ''} onChange={(e) => set('taxNumber', e.target.value)} placeholder="143/256/12345"/></Field>
          <Field label="USt-IdNr." hint="Für innergem. Lieferungen"><TextInput value={form.ust || ''} onChange={(e) => set('ust', e.target.value)} placeholder="DE123456789"/></Field>
          <Field label="Handelsregister-Nr." hint="Nur bei eingetragener Firma"><TextInput value={form.handelsregister || ''} onChange={(e) => set('handelsregister', e.target.value)} placeholder="HRB 123456"/></Field>
          <Field label="Amtsgericht"><TextInput value={form.amtsgericht || ''} onChange={(e) => set('amtsgericht', e.target.value)} placeholder="München"/></Field>
        </div>
      </div>
    </>
  );

  const BankSection = (
    <>
      <div style={card}>
        <SectionTitle>Bankverbindung</SectionTitle>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 4 }}>
          <Field label="IBAN" style={{ gridColumn: '1 / -1' }}><TextInput value={form.iban || ''} onChange={(e) => set('iban', e.target.value)} placeholder="DE12 3456 7890 1234 5678 90"/></Field>
          <Field label="BIC"><TextInput value={form.bic || ''} onChange={(e) => set('bic', e.target.value)} placeholder="BYLADEM1MUC"/></Field>
          <Field label="Bank"><TextInput value={form.bankName || ''} onChange={(e) => set('bankName', e.target.value)} placeholder="Bayerische Landesbank"/></Field>
        </div>
      </div>

      <div style={card}>
        <SectionTitle>Umsatzsteuer</SectionTitle>
        <Row title="Kleinunternehmer (§ 19 UStG)" sub="Rechnungen werden ohne MwSt. ausgewiesen.">
          <Toggle on={!!form.kleinunternehmer} onClick={() => set('kleinunternehmer', !form.kleinunternehmer)}/>
        </Row>
        <Row title="Standard-MwSt.-Satz" sub={form.kleinunternehmer ? 'Nicht aktiv – Kleinunternehmer.' : 'Wird auf neue Rechnungspositionen vorbelegt.'} last>
          <Segmented value={String(form.mwstSatz)} onChange={(v) => set('mwstSatz', Number(v))} options={[['19', '19 %'], ['7', '7 %'], ['0', '0 %']]} size="sm"/>
        </Row>
      </div>
    </>
  );

  const LogistikSection = (
    <>
      <div style={card}>
        <SectionTitle>Lager & Startadresse</SectionTitle>
        <Field label="Adresse" hint="Ausgangspunkt für km-Berechnung."><TextInput value={form.lagerAddress || ''} onChange={(e) => set('lagerAddress', e.target.value)} placeholder="Bahnhofstr. 18, 82110 Germering"/></Field>
      </div>

      <div style={card}>
        <SectionTitle>Lieferpreise</SectionTitle>
        <Row title="Preis pro km" sub="Berechnungsgrundlage für Lieferung.">
          <NumInput value={form.kmRate} onChange={(e) => setNum('kmRate', e.target.value.replace(',', '.'), 0)} suffix="€/km" width={90}/>
        </Row>
        <Row title="Pauschale" sub="Fixer Sockelbetrag pro Lieferung.">
          <NumInput value={form.pauschale} onChange={(e) => setNum('pauschale', e.target.value, 0)} suffix="€" width={90}/>
        </Row>
        <Row title="Standard-Fahrten" sub="Hin- & Rückweg für Anlieferung + Abholung." last>
          <Segmented value={String(form.tripFactor)} onChange={(v) => set('tripFactor', Number(v))} options={[['1', '1×'], ['2', '2×'], ['4', '4×']]} size="sm"/>
        </Row>
        <div style={{ marginTop: 14, padding: '12px 14px', background: t.accentSoft, borderRadius: 12, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <div style={{ fontSize: 18, lineHeight: 1 }}>💡</div>
          <div style={{ flex: 1, fontSize: 12.5, color: t.text, lineHeight: 1.5 }}>
            <strong>Beispiel 10 km:</strong> {(10 * (Number(form.tripFactor) || 1) * (Number(form.kmRate) || 0) + (Number(form.pauschale) || 0)).toFixed(2).replace('.', ',')} €
            <span style={{ color: t.textSec }}> · {String(form.kmRate).replace('.', ',')} €/km × {form.tripFactor} Fahrten + {form.pauschale} € Pauschale</span>
          </div>
        </div>
      </div>
    </>
  );

  const DokumenteSection = (
    <>
      <div style={card}>
        <SectionTitle>Nummern-Schemata</SectionTitle>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 4 }}>
          <Field label="Rechnungsnummern" hint="{YYYY} = Jahr · {####} = Zähler"><TextInput value={form.invoiceScheme || ''} onChange={(e) => set('invoiceScheme', e.target.value)} placeholder="RE-{YYYY}-{####}"/></Field>
          <Field label="Vertragsnummern"><TextInput value={form.contractScheme || ''} onChange={(e) => set('contractScheme', e.target.value)} placeholder="MV-{YYYY}-{####}"/></Field>
        </div>
        <div style={{ marginTop: 10, padding: '10px 12px', background: t.cardAlt, borderRadius: 10, fontSize: 12, color: t.textSec, fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace' }}>
          Nächste Rechnung: {String(form.invoiceScheme || '').replace('{YYYY}', new Date().getFullYear()).replace('{####}', '0042')}
        </div>
      </div>

      <div style={card}>
        <SectionTitle>Standard-Konditionen</SectionTitle>
        <Row title="Zahlungsfrist" sub="Tage bis zur Fälligkeit auf Rechnungen.">
          <NumInput value={form.paymentDays} onChange={(e) => setNum('paymentDays', e.target.value, 14)} suffix="Tage" width={70}/>
        </Row>
        <Row title="Standard-Kaution" sub="Vorgeschlagener Wert bei neuen Mietaufträgen." last>
          <NumInput value={form.defaultDeposit} onChange={(e) => setNum('defaultDeposit', e.target.value, 0)} suffix="€" width={90}/>
        </Row>
      </div>

      <div style={card}>
        <SectionTitle>Rechnungs-Fußzeile</SectionTitle>
        <textarea value={form.invoiceFooter || ''} onChange={(e) => set('invoiceFooter', e.target.value)} rows={4}
          style={{ width: '100%', padding: '11px 13px', borderRadius: 10, border: `1px solid ${t.inputBorder}`, background: t.inputBg, fontSize: 13, color: t.text, fontFamily: 'inherit', lineHeight: 1.55, resize: 'vertical', boxSizing: 'border-box' }}
          placeholder="Vielen Dank für Ihren Auftrag. Zahlbar ohne Abzug innerhalb der Zahlungsfrist."/>
        <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 8 }}>Erscheint unter jeder generierten Rechnung.</div>
      </div>
    </>
  );

  const ErinnerungenSection = (
    <>
      <div style={card}>
        <SectionTitle>Push-Benachrichtigungen</SectionTitle>
        <div style={{ fontSize: 12.5, color: t.textSec, marginTop: -4, marginBottom: 6 }}>macOS-Mitteilungen, wenn etwas zu tun ist.</div>

        <Row title="Vertrag läuft bald ab" sub={form.remindContract ? `Vorlauf: ${form.remindContractDays} Tag${form.remindContractDays === 1 ? '' : 'e'} vor Mietende.` : 'Deaktiviert'}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            {form.remindContract && (
              <NumInput value={form.remindContractDays} onChange={(e) => setNum('remindContractDays', e.target.value, 3)} suffix="Tage" width={70}/>
            )}
            <Toggle on={!!form.remindContract} onClick={() => set('remindContract', !form.remindContract)}/>
          </div>
        </Row>

        <Row title="Rückgabe überfällig" sub="Sofortige Erinnerung wenn ein Vorgang nicht zurückgegeben wurde.">
          <Toggle on={!!form.remindReturn} onClick={() => set('remindReturn', !form.remindReturn)}/>
        </Row>

        <Row title="Wartung fällig" sub="Erinnerung wenn ein Gerät seinen Wartungstermin erreicht.">
          <Toggle on={!!form.remindMaintenance} onClick={() => set('remindMaintenance', !form.remindMaintenance)}/>
        </Row>

        <Row title="Rechnung überfällig" sub={form.remindInvoice ? `Erinnerung ${form.remindInvoiceDays} Tage nach Zahlungsfrist.` : 'Deaktiviert'} last>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            {form.remindInvoice && (
              <NumInput value={form.remindInvoiceDays} onChange={(e) => setNum('remindInvoiceDays', e.target.value, 7)} suffix="Tage" width={70}/>
            )}
            <Toggle on={!!form.remindInvoice} onClick={() => set('remindInvoice', !form.remindInvoice)}/>
          </div>
        </Row>
      </div>
    </>
  );

  const DarstellungSection = (
    <>
      <div style={card}>
        <SectionTitle>Erscheinungsbild</SectionTitle>
        <Row title="Modus" sub="Hell oder Dunkel – passt sich der gesamten App an." last>
          <Segmented value={dark ? 'dark' : 'light'} onChange={(v) => { if ((v === 'dark') !== dark) toggleDark(); }} options={[['light', '☀︎ Hell'], ['dark', '☾ Dunkel']]}/>
        </Row>
      </div>

      <div style={{ ...card, opacity: 0.9 }}>
        <SectionTitle>Über</SectionTitle>
        <div style={{ fontSize: 13, color: t.textSec, lineHeight: 1.6 }}>RentFlow Manager · Desktop-Edition für macOS. Verwaltung von Vermietungen, Equipment, Terminen und Finanzen — synchron zur mobilen App.</div>
      </div>
    </>
  );

  // ────────────── Datensicherung helpers ──────────────
  const fmtBytes = (n) => {
    if (!n || n < 1024) return (n || 0) + ' B';
    if (n < 1024 * 1024) return (n / 1024).toFixed(1).replace('.', ',') + ' KB';
    return (n / (1024 * 1024)).toFixed(2).replace('.', ',') + ' MB';
  };
  const fmtBackupDate = (iso) => {
    if (!iso) return '';
    const d2 = new Date(iso);
    const today = new Date(); today.setHours(0,0,0,0);
    const day0 = new Date(d2); day0.setHours(0,0,0,0);
    const diff = Math.round((today - day0) / 86400000);
    const time = String(d2.getHours()).padStart(2, '0') + ':' + String(d2.getMinutes()).padStart(2, '0');
    if (diff === 0) return 'Heute, ' + time;
    if (diff === 1) return 'Gestern, ' + time;
    return fmtDateDE(fmtDateISO(d2)) + ', ' + time;
  };

  const protokolleCount = (d.docs || []).filter((x) => x.kind === 'protokoll').length;
  const dokumenteCount  = (d.docs || []).filter((x) => x.kind !== 'protokoll').length;
  const aufgabenCount   = ((d.tasks && d.tasks.items) || []).filter((x) => !x.done).length;

  const buildBackupPayload = () => ({
    schema: 'rentflow-backup',
    version: 1,
    app: 'RentFlow Manager Desktop',
    createdISO: new Date().toISOString(),
    company: form,
    equipment: d.equipment || [],
    rentals:   d.rentals   || [],
    events:    d.events    || [],
    tasks:     d.tasks     || { items: [], autoDone: {} },
    categories:d.categories|| [],
    docs:      d.docs      || [],
    blocked:   d.blocked   || [],
  });
  const currentPayloadSize = useMemo(() => {
    try { return new Blob([JSON.stringify(buildBackupPayload())]).size; } catch (e) { return 0; }
  }, [d.equipment, d.rentals, d.events, d.tasks, d.categories, d.docs, d.blocked, form]);

  const doExport = () => {
    const payload = buildBackupPayload();
    const json = JSON.stringify(payload, null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    const stamp = new Date().toISOString().slice(0, 16).replace(/[:T]/g, '-');
    a.href = url; a.download = 'rentflow-backup-' + stamp + '.json';
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1500);
    const counts = {
      equipment: (d.equipment || []).length, rentals: (d.rentals || []).length,
      events: (d.events || []).length, docs: (d.docs || []).length,
      tasks: ((d.tasks && d.tasks.items) || []).length, blocked: (d.blocked || []).length,
    };
    setLastBackup({ dateISO: new Date().toISOString(), size: blob.size, counts });
    toast('Backup heruntergeladen');
  };

  const onPickImport = (e) => {
    const file = e.target.files && e.target.files[0]; if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      try {
        const payload = JSON.parse(String(reader.result));
        if (!payload || payload.schema !== 'rentflow-backup') throw new Error('Ungültige Backup-Datei');
        setPendingImport({ payload, name: file.name, size: file.size });
      } catch (err) {
        toast('Datei ist kein gültiges RentFlow-Backup');
      }
    };
    reader.readAsText(file);
    e.target.value = '';
  };
  const applyImport = () => {
    if (!pendingImport) return;
    const p = pendingImport.payload;
    if (p.equipment   && d.setEquipment)  d.setEquipment(p.equipment);
    if (p.rentals     && d.setRentals)    d.setRentals(p.rentals);
    if (p.events      && d.setEvents)     d.setEvents(p.events);
    if (p.tasks       && d.setTasks)      d.setTasks(p.tasks);
    if (p.categories  && d.setCategories) d.setCategories(p.categories);
    if (p.docs        && d.setDocs)       d.setDocs(p.docs);
    if (p.blocked     && d.setBlocked)    d.setBlocked(p.blocked);
    if (p.company)                        setCompany({ ...DEFAULT_COMPANY, ...p.company });
    setPendingImport(null);
    toast('Daten wiederhergestellt');
  };
  const doReset = () => {
    if (d.setEquipment)  d.setEquipment(SEED_EQUIPMENT);
    if (d.setRentals)    d.setRentals(SEED_RENTALS);
    if (d.setEvents)     d.setEvents(SEED_EVENTS);
    if (d.setTasks)      d.setTasks({ items: [], autoDone: {} });
    if (d.setCategories) d.setCategories(['Tontechnik', 'Anhänger', 'Licht', 'Sonstiges']);
    if (d.setDocs)       d.setDocs(typeof SEED_DOCS !== 'undefined' ? SEED_DOCS : []);
    if (d.setBlocked)    d.setBlocked([]);
    setCompany(DEFAULT_COMPANY);
    setLastBackup(null);
    setConfirmReset(false);
    toast('Alle Daten zurückgesetzt');
  };

  const DataRow = ({ label, value, last }) => (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '13px 0', borderBottom: last ? 'none' : `0.5px solid ${t.sep}` }}>
      <div style={{ fontSize: 14, color: t.text }}>{label}</div>
      <div style={{ fontSize: 14, color: t.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
    </div>
  );

  const hasBackup = !!lastBackup;
  const DatensicherungSection = (
    <>
      {/* Status card */}
      <div style={{ ...card, padding: 18, display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ width: 52, height: 52, borderRadius: 13, background: hasBackup ? (t.green || '#34C759') + '22' : '#FF9F0A22', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon d={hasBackup ? icons.check : icons.download} color={hasBackup ? (t.green || '#34C759') : '#FF9F0A'} size={24} sw={2.2}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: -0.2 }}>{hasBackup ? 'Letzte Sicherung' : 'Noch keine Sicherung'}</div>
          <div style={{ fontSize: 13, color: t.textSec, marginTop: 2 }}>
            {hasBackup ? (fmtBackupDate(lastBackup.dateISO) + ' · ' + fmtBytes(lastBackup.size)) : 'Erstelle ein Backup um deine Daten zu sichern.'}
          </div>
        </div>
        {hasBackup && (
          <Button variant="soft" size="sm" onClick={() => setLastBackup(null)}>Verwerfen</Button>
        )}
      </div>

      {/* Current data */}
      <div style={card}>
        <SectionTitle>Aktueller Datenbestand</SectionTitle>
        <div style={{ marginTop: 4 }}>
          <DataRow label="Equipment"    value={(d.equipment || []).length}/>
          <DataRow label="Mietverträge" value={(d.rentals   || []).length}/>
          <DataRow label="Termine"      value={(d.events    || []).length}/>
          <DataRow label="Protokolle"   value={protokolleCount}/>
          <DataRow label="Aufgaben"     value={aufgabenCount}/>
          <DataRow label="Dokumente"    value={dokumenteCount}/>
          <DataRow label="Sperrzeiten"  value={(d.blocked || []).length}/>
          <DataRow label="Backup-Grösse" value={fmtBytes(currentPayloadSize)} last/>
        </div>
      </div>

      {/* Sicherung erstellen */}
      <div style={card}>
        <SectionTitle>Sicherung erstellen</SectionTitle>
        <Pressable onClick={doExport} scale={0.99} style={{ marginTop: 6 }}>
          <div style={{ padding: '16px 18px', borderRadius: 12, background: t.accent, color: '#fff', display: 'flex', alignItems: 'center', gap: 14, boxShadow: '0 6px 18px rgba(0,122,255,0.32)' }}>
            <div style={{ width: 38, height: 38, borderRadius: 10, background: 'rgba(255,255,255,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon d={icons.download} color="#fff" size={20} sw={2.2}/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: -0.1 }}>Backup exportieren</div>
              <div style={{ fontSize: 12.5, opacity: 0.85, marginTop: 1 }}>Als .json-Datei herunterladen</div>
            </div>
            <Icon d={icons.chev} color="#fff" size={16} sw={2.4}/>
          </div>
        </Pressable>
        <div style={{ fontSize: 12, color: t.textSec, marginTop: 12, lineHeight: 1.55 }}>
          Enthält alle Mietverträge, Equipment, Termine, Dokumente, Protokolle und das Firmenprofil. Bewahre die Datei an einem sicheren Ort auf — z. B. iCloud Drive.
        </div>
      </div>

      {/* Sicherung wiederherstellen */}
      <div style={card}>
        <SectionTitle>Sicherung wiederherstellen</SectionTitle>
        <input ref={importRef} type="file" accept="application/json,.json" style={{ display: 'none' }} onChange={onPickImport}/>
        <Pressable onClick={() => importRef.current && importRef.current.click()} scale={0.99} style={{ marginTop: 6 }} hoverBg={t.chip}>
          <div style={{ padding: '14px 16px', borderRadius: 12, background: t.cardAlt, display: 'flex', alignItems: 'center', gap: 14, border: `0.5px solid ${t.sep}` }}>
            <div style={{ width: 38, height: 38, borderRadius: 10, background: t.accent + '22', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon d={icons.upload} color={t.accent} size={20} sw={2.2}/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, letterSpacing: -0.1 }}>Backup importieren</div>
              <div style={{ fontSize: 12.5, color: t.textSec, marginTop: 1 }}>.json-Datei vom Gerät auswählen</div>
            </div>
            <Icon d={icons.chev} color={t.textTer} size={14} sw={2.2}/>
          </div>
        </Pressable>
        <div style={{ fontSize: 12, color: t.textSec, marginTop: 12, lineHeight: 1.55 }}>
          Beim Import werden alle aktuellen Daten in der App ersetzt. Du wirst vorher gefragt.
        </div>
      </div>

      {/* Gefahrenzone */}
      <div style={card}>
        <SectionTitle>Gefahrenzone</SectionTitle>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 18, marginTop: 4 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>Alle Daten zurücksetzen</div>
            <div style={{ fontSize: 12.5, color: t.textSec, marginTop: 3, lineHeight: 1.5 }}>Löscht lokal gespeicherte Daten und stellt die Beispieldaten wieder her.</div>
          </div>
          <Pressable onClick={() => setConfirmReset(true)} scale={0.97}>
            <div style={{ padding: '9px 16px', borderRadius: 10, background: (t.red || '#FF3B30') + '18', color: (t.red || '#FF3B30'), fontSize: 13.5, fontWeight: 600, whiteSpace: 'nowrap' }}>Zurücksetzen</div>
          </Pressable>
        </div>
      </div>
    </>
  );

  const SECTION_MAP = {
    stammdaten:     StammdatenSection,
    bank:           BankSection,
    logistik:       LogistikSection,
    dokumente:      DokumenteSection,
    erinnerungen:   ErinnerungenSection,
    datensicherung: DatensicherungSection,
    darstellung:    DarstellungSection,
  };

  return (
    <>
      <Toolbar title="Einstellungen" subtitle={TABS.find((x) => x.id === tab)?.label || 'Firmenprofil'}>
        {dirty && <Button variant="soft" size="sm" onClick={() => setForm(merged)}>Verwerfen</Button>}
        {dirty && <Button variant="primary" icon={icons.check} onClick={() => { setCompany(form); toast('Gespeichert'); }}>Speichern</Button>}
      </Toolbar>
      <div style={{ flex: 1, display: 'flex', minHeight: 0, background: t.bg }}>
        {/* Left rail */}
        <div style={{ width: 220, flexShrink: 0, padding: '20px 12px', borderRight: `0.5px solid ${t.sep}`, overflow: 'auto' }}>
          {TABS.map((tb) => {
            const sel = tab === tb.id;
            return (
              <Pressable key={tb.id} onClick={() => setTab(tb.id)} scale={0.99} hoverBg={sel ? undefined : t.chip} style={{ borderRadius: 10, marginBottom: 2 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 11px', borderRadius: 10, background: sel ? t.chipStrong : 'transparent' }}>
                  <Icon d={tb.icon} color={sel ? t.text : t.textSec} size={16} sw={sel ? 2 : 1.8}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: sel ? 600 : 500, color: t.text }}>{tb.label}</div>
                    <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tb.sub}</div>
                  </div>
                </div>
              </Pressable>
            );
          })}
        </div>

        {/* Right pane */}
        <Scroll style={{ background: t.bg }}>
          <div style={{ maxWidth: 720, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 18 }}>
            {SECTION_MAP[tab]}
          </div>
        </Scroll>
      </div>
    </>
  );
}

Object.assign(window, { ScreenDocuments, ScreenProfile, DEFAULT_TEMPLATES, DocPaper, buildTokens });
