// Schnelltexte tab — quick copy-to-clipboard text templates for WhatsApp/Kleinanzeigen.
// Three panes: template list (with add/edit/delete) · rental picker · live preview with Kopieren.

function DocsSchnelltexte({ rentals, equipment, company, docs, setDocs, initialRentalId }) {
  const t = useTheme();
  const toast = useToast();
  const [templates, setTemplates] = useLocal('rf-d-qtext-tpls-v1', QUICK_TEXT_TEMPLATES);
  const [selTplId, setSelTplId] = useState(templates[0] && templates[0].id);
  const [selRentalId, setSelRentalId] = useState(initialRentalId || (rentals[0] && rentals[0].id));
  const [editingTpl, setEditingTpl] = useState(false);
  const [tplSnapshot, setTplSnapshot] = useState(null); // Snapshot taken when editor opens, used for „Verwerfen“
  const [confirmDel, setConfirmDel] = useState(null);

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

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

  const filled = useMemo(() => tpl && r ? fillQuickText(tpl.body, r, eq, company) : '', [tpl && tpl.id, tpl && tpl.body, r && r.id, eq && eq.id, company]);

  const [editedBody, setEditedBody] = useState(filled);
  useEffect(() => { setEditedBody(filled); }, [filled]);

  const copy = () => {
    if (!editedBody) return;
    try {
      navigator.clipboard.writeText(editedBody);
      toast('In die Zwischenablage kopiert');
    } catch (err) { toast('Kopieren fehlgeschlagen'); }
  };
  const saveToArchive = () => {
    if (!r || !tpl) return;
    const doc = {
      id: 'd-' + Date.now(),
      kind: tpl.kind || 'custom',
      format: 'text',
      title: tpl.name,
      rentalId: r.id,
      templateId: tpl.id,
      body: editedBody,
      createdISO: todayISO(),
    };
    setDocs((prev) => [doc, ...prev]);
    toast('Im Archiv gespeichert');
  };
  const patchTpl = (patch) => setTemplates((prev) => prev.map((x) => x.id === tpl.id ? { ...x, ...patch } : x));

  // Open editor: snapshot current template so we can restore on „Verwerfen“
  const openEditor = () => { if (tpl) { setTplSnapshot({ ...tpl }); setEditingTpl(true); } };
  const closeEditor = () => { setTplSnapshot(null); setEditingTpl(false); };
  const discardTplEdits = () => {
    if (!tplSnapshot) return;
    setTemplates((prev) => prev.map((x) => x.id === tplSnapshot.id ? { ...tplSnapshot } : x));
    toast('Änderungen verworfen');
  };
  const tplIsDirty = !!(tplSnapshot && tpl && (
    tpl.name !== tplSnapshot.name || tpl.body !== tplSnapshot.body ||
    tpl.icon !== tplSnapshot.icon || tpl.color !== tplSnapshot.color ||
    tpl.desc !== tplSnapshot.desc
  ));

  // Built-in templates can be reset to their original definition
  const builtIn = tpl && QUICK_TEXT_TEMPLATES.find((x) => x.id === tpl.id);
  const tplDiffersFromBuiltIn = !!(builtIn && (
    builtIn.name !== tpl.name || builtIn.body !== tpl.body ||
    builtIn.icon !== tpl.icon || builtIn.color !== tpl.color ||
    builtIn.desc !== tpl.desc
  ));
  const resetToBuiltIn = () => {
    if (!builtIn) return;
    setTemplates((prev) => prev.map((x) => x.id === builtIn.id ? { ...builtIn } : x));
    toast('Auf Standard zurückgesetzt');
  };
  const addTpl = () => {
    const id = 'qt-' + Date.now();
    const fresh = { id, name: 'Neue Vorlage', icon: '📝', color: '#5856D6', kind: 'custom', desc: 'Eigene Schnellnachricht', body: 'Hallo {{name}},\n\n…\n\nViele Grüße\n{{firma}}' };
    setTemplates((prev) => [...prev, fresh]);
    setSelTplId(id); setEditingTpl(true);
  };
  const delTpl = () => {
    setTemplates((prev) => prev.filter((x) => x.id !== tpl.id));
    setSelTplId((templates.find((x) => x.id !== tpl.id) || templates[0] || { id: null }).id);
    setConfirmDel(null);
    setEditingTpl(false);
    toast('Vorlage gelöscht');
  };

  return (
    <div style={{ flex: 1, display: 'flex', minHeight: 0, minWidth: 0 }}>
      {/* ── Sidebar: template list ── */}
      <div style={{ width: 280, flexShrink: 0, borderRight: `0.5px solid ${t.sep}`, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div style={{ padding: '14px 16px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>Schnelltexte</div>
          <Pressable onClick={addTpl} scale={0.94}>
            <div title="Neue Vorlage" 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.plus} color={t.text} size={11} sw={2.4}/>Neu
            </div>
          </Pressable>
        </div>
        <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding: '4px 12px 12px', display: 'flex', flexDirection: 'column', gap: 3 }}>
          {templates.map((d) => {
            const sel = selTplId === d.id;
            return (
              <Pressable key={d.id} onClick={() => setSelTplId(d.id)} scale={0.99} hoverBg={sel ? undefined : t.cardAlt}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 10px', borderRadius: 11, background: sel ? t.chip : 'transparent', border: sel ? `1px solid ${t.sep}` : '1px solid transparent' }}>
                  <div style={{ width: 32, height: 32, borderRadius: 9, background: d.color + '1e', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, flexShrink: 0, color: t.textSec }}>{d.icon || (
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M4 6h12M4 12h12M4 18h8"/></svg>
                  )}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</div>
                    <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.desc}</div>
                  </div>
                </div>
              </Pressable>
            );
          })}
        </div>
      </div>

      {/* ── Middle: rental picker ── */}
      <div style={{ width: 260, flexShrink: 0, borderRight: `0.5px solid ${t.sep}`, display: 'flex', flexDirection: 'column', minHeight: 0, background: t.cardAlt }}>
        <div style={{ padding: '14px 16px 6px', fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>Mietvorgang wählen</div>
        <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding: '4px 10px 10px', display: 'flex', flexDirection: 'column', gap: 2 }}>
          {rentals.map((x) => {
            const e = equipment.find((q) => q.id === x.equipmentId);
            const sel = x.id === selRentalId;
            return (
              <Pressable key={x.id} onClick={() => setSelRentalId(x.id)} scale={0.99} hoverBg={sel ? undefined : t.card}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 10, background: sel ? t.card : 'transparent', border: sel ? `1px solid ${t.sep}` : '1px solid transparent' }}>
                  <Avatar name={x.tenantName} size={30}/>
                  <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>

      {/* ── Right: preview / editor ── */}
      <div className="rf-scroll" style={{ flex: 1, minWidth: 0, overflow: 'auto', padding: '20px 24px 40px' }}>
        {tpl ? (
          <div style={{ maxWidth: 640 }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 14 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                {editingTpl ? (
                  <>
                    <input value={tpl.name} onChange={(e) => patchTpl({ name: e.target.value })} placeholder="Name der Vorlage"
                      style={{ width: '100%', fontSize: 22, fontWeight: 700, color: t.text, background: 'transparent', border: 'none', borderBottom: `1.5px solid ${t.accent}`, outline: 'none', letterSpacing: -0.5, boxSizing: 'border-box', padding: '2px 0' }}/>
                    <input value={tpl.desc || ''} onChange={(e) => patchTpl({ desc: e.target.value })} placeholder="Kurze Beschreibung"
                      style={{ width: '100%', fontSize: 13, color: t.textSec, background: 'transparent', border: 'none', borderBottom: `1px dashed ${t.sep}`, outline: 'none', boxSizing: 'border-box', padding: '4px 0', marginTop: 4 }}/>
                  </>
                ) : (
                  <>
                    <div style={{ fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: -0.5 }}>{tpl.name}</div>
                    <div style={{ fontSize: 13, color: t.textSec, marginTop: 3 }}>{tpl.desc} · für {r ? r.tenantName : '—'}</div>
                  </>
                )}
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                {editingTpl && builtIn && <Button variant="soft" size="sm" icon={icons.refresh} onClick={resetToBuiltIn} disabled={!tplDiffersFromBuiltIn} title="Vorlage auf Standard zurücksetzen">Auf Standard</Button>}
                {editingTpl && <Button variant="soft" size="sm" icon={icons.refresh} onClick={discardTplEdits} disabled={!tplIsDirty}>Verwerfen</Button>}
                <Button variant={editingTpl ? 'accent' : 'soft'} size="sm" icon={editingTpl ? icons.check : icons.edit} onClick={() => editingTpl ? closeEditor() : openEditor()}>{editingTpl ? 'Fertig' : 'Vorlage bearbeiten'}</Button>
                <IconBtn icon={icons.trash} color={t.red} onClick={() => setConfirmDel(tpl)} title="Vorlage löschen"/>
              </div>
            </div>

            {editingTpl && (
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Symbol &amp; Farbe</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 14px', borderRadius: 12, background: t.cardAlt, border: `0.5px solid ${t.sep}`, marginBottom: 14 }}>
                  <div style={{ width: 52, height: 52, borderRadius: 13, background: tpl.color + '22', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 26, flexShrink: 0, color: t.textSec }}>{tpl.icon || (
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><circle cx="12" cy="12" r="9"/><path d="M5.5 5.5l13 13"/></svg>
                  )}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, marginBottom: 4 }}>Emoji</div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                      <Pressable onClick={() => patchTpl({ icon: '' })} scale={0.9}>
                        <div title="Kein Emoji" style={{ width: 30, height: 30, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', background: !tpl.icon ? t.chip : 'transparent', border: !tpl.icon ? `1px solid ${t.sep}` : `1px dashed ${t.sep}`, color: t.textSec }}>
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="12" r="9"/><path d="M5.5 5.5l13 13"/></svg>
                        </div>
                      </Pressable>
                      {['📝','💬','📲','📧','📞','📅','✅','💰','🧾','📋','📦','🔑','⚡','⭐','🎉','⚠️'].map((e) => (
                        <Pressable key={e} onClick={() => patchTpl({ icon: e })} scale={0.9}>
                          <div style={{ width: 30, height: 30, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, background: tpl.icon === e ? t.chip : 'transparent', border: tpl.icon === e ? `1px solid ${t.sep}` : '1px solid transparent' }}>{e}</div>
                        </Pressable>
                      ))}
                      <input value={tpl.icon || ''} onChange={(ev) => patchTpl({ icon: ev.target.value.slice(0, 4) })} maxLength={4} placeholder="…"
                        style={{ width: 50, height: 30, borderRadius: 8, border: `1px solid ${t.inputBorder}`, background: t.inputBg, color: t.text, textAlign: 'center', fontSize: 14, outline: 'none', boxSizing: 'border-box' }}/>
                    </div>
                  </div>
                  <div style={{ width: 1, height: 44, background: t.sep }}/>
                  <div style={{ flexShrink: 0 }}>
                    <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, marginBottom: 4 }}>Farbe</div>
                    <div style={{ display: 'flex', gap: 6 }}>
                      {['#007AFF','#34C759','#FF9500','#FF3B30','#AF52DE','#5856D6','#FF2D55','#8E8E93'].map((c) => (
                        <Pressable key={c} onClick={() => patchTpl({ color: c })} scale={0.85}>
                          <div title={c} style={{ width: 22, height: 22, borderRadius: 11, background: c, border: tpl.color === c ? `2.5px solid ${t.text}` : `2px solid ${t.card}`, boxShadow: tpl.color === c ? '0 0 0 1px ' + t.sep : 'none' }}/>
                        </Pressable>
                      ))}
                    </div>
                  </div>
                </div>

                <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Vorlagentext (mit Platzhaltern)</div>
                <textarea rows={10} value={tpl.body} onChange={(e) => patchTpl({ body: e.target.value })}
                  style={{ width: '100%', fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace', fontSize: 12.5, lineHeight: 1.55, padding: '12px 14px', border: `1px solid ${t.inputBorder}`, borderRadius: 10, background: t.inputBg, color: t.text, resize: 'vertical', outline: 'none', boxSizing: 'border-box' }}/>
                <div style={{ marginTop: 10, padding: '10px 12px', 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: 6 }}>Verfügbare Platzhalter</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                    {QUICK_TOKENS.map(([k, lab]) => (
                      <span key={k} title={lab} style={{ fontSize: 10.5, fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace', padding: '2px 6px', borderRadius: 5, background: t.chip, color: t.text, cursor: 'help' }}>{`{{${k}}}`}</span>
                    ))}
                  </div>
                </div>
              </div>
            )}

            <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Vorschau · ausgefüllt</div>
            <div style={{ position: 'relative', background: t.card, border: `0.5px solid ${t.sep}`, borderRadius: 14, boxShadow: t.shadowCard, overflow: 'hidden' }}>
              <textarea rows={Math.max(10, (editedBody || '').split('\n').length + 1)} value={editedBody} onChange={(e) => setEditedBody(e.target.value)}
                style={{ width: '100%', fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif', fontSize: 14, lineHeight: 1.55, padding: '18px 20px', border: 'none', background: 'transparent', color: t.text, resize: 'vertical', outline: 'none', boxSizing: 'border-box', minHeight: 200 }}/>
            </div>

            <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
              <Button variant="primary" icon={icons.download} onClick={copy} disabled={!editedBody}>Kopieren</Button>
              <Button variant="soft" icon={icons.archive} onClick={saveToArchive} disabled={!r}>Im Archiv speichern</Button>
              <div style={{ flex: 1 }}/>
              <div style={{ fontSize: 11, color: t.textSec, alignSelf: 'center' }}>{editedBody !== filled ? <span style={{ color: t.accent, fontWeight: 600 }}>· bearbeitet · </span> : null}{(editedBody || '').length} Zeichen</div>
            </div>
          </div>
        ) : (
          <Empty icon={icons.doc} title="Keine Vorlage gewählt"/>
        )}
      </div>

      <Confirm open={!!confirmDel} title="Vorlage löschen?"
        message={confirmDel ? `„${confirmDel.name}" wird unwiderruflich entfernt.` : ''}
        onConfirm={delTpl} onClose={() => setConfirmDel(null)}/>
    </div>
  );
}

Object.assign(window, { DocsSchnelltexte });
