// Einstellungen — sub-views part 2: Dokumente, Erinnerungen, Darstellung.

const { useState: useStateE2, useEffect: useEffectE2 } = React;

// ─────────────────────────────────────────────────────────────
// Dokumente — number patterns, payment defaults, footer + PDF template + accent
// ─────────────────────────────────────────────────────────────
function DokumenteSettingsView({ t, c, set, onBack, onClose }) {
  const nextInvoiceNo = previewNumber(c.invoicePattern, c.invoiceCounter || 1);
  const nextContractNo = previewNumber(c.contractPattern, c.contractCounter || 1);

  return (
    <div>
      <SubHeader title="Dokumente" onBack={onBack} onClose={onClose} t={t} />

      <GroupLabel t={t}>Nummern-Schemata</GroupLabel>
      <GroupCard t={t}>
        <InputRow label="Rechnungsnummern" value={c.invoicePattern}
        onChange={(v) => set({ invoicePattern: v })}
        placeholder="RE-{YYYY}-{####}" t={t} />
        <InputRow label="Vertragsnummern" value={c.contractPattern}
        onChange={(v) => set({ contractPattern: v })}
        placeholder="MV-{YYYY}-{####}" t={t} last />
      </GroupCard>
      <HintLine t={t}>{'{YYYY} = Jahr  ·  {YY} = Kurzjahr  ·  {####} = Zähler'}</HintLine>

      {/* Preview tile */}
      <div style={{ padding: '10px 16px 0' }}>
        <div style={{
          background: t.cardAlt, borderRadius: 12, padding: '12px 14px',
          fontFamily: 'ui-monospace, SF Mono, Menlo, monospace',
          fontSize: 13, color: t.text, lineHeight: 1.7
        }}>
          <div><span style={{ color: t.textSec }}>Nächste Rechnung:</span> <strong>{nextInvoiceNo}</strong></div>
          <div><span style={{ color: t.textSec }}>Nächster Vertrag:</span> <strong>{nextContractNo}</strong></div>
        </div>
      </div>

      <GroupLabel t={t}>Standard-Konditionen</GroupLabel>
      <GroupCard t={t}>
        <ListRow t={t}
        title="Zahlungsfrist" sub="Tage bis zur Fälligkeit auf Rechnungen."
        right={<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <NumberPill t={t} value={c.paymentDays ?? ''} onChange={(v) => set({ paymentDays: v === '' ? '' : v })} />
            <span style={{ fontSize: 13, color: t.textSec, minWidth: 32 }}>Tage</span>
          </div>} />
        
        <ListRow t={t} last
        title="Standard-Kaution" sub="Vorgeschlagener Wert bei neuen Mietaufträgen."
        right={<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <NumberPill t={t} width={64} value={c.defaultDeposit ?? ''} onChange={(v) => set({ defaultDeposit: v === '' ? '' : v })} />
            <span style={{ fontSize: 13, color: t.textSec, minWidth: 32 }}>€</span>
          </div>} />
        
      </GroupCard>

      {/* PDF template + accent (kept from previous Firmenprofil) */}
      <GroupLabel t={t}>PDF-Vorlage</GroupLabel>
      <div style={{ padding: '0 16px', display: 'flex', gap: 8 }}>
        {PDF_TEMPLATES.map((tp) => {
          const sel = (c.template || 'modern') === tp.id;
          return (
            <Pressable key={tp.id} onClick={() => set({ template: tp.id })} scale={0.96} style={{ flex: 1 }}>
              <div style={{
                padding: '10px 8px', borderRadius: 12, textAlign: 'center',
                background: sel ? t.accentSoft : t.card,
                border: sel ? `1.5px solid ${t.accent}` : `0.5px solid ${t.sep}`,
                boxShadow: sel ? 'none' : t.shadowCard
              }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: sel ? t.accent : t.text }}>{tp.label}</div>
                <div style={{ fontSize: 10.5, color: t.textSec, marginTop: 2, lineHeight: 1.3 }}>{tp.desc}</div>
              </div>
            </Pressable>);

        })}
      </div>

      <div style={{ padding: '12px 16px 0' }}>
        <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>Akzentfarbe</div>
        <div style={{ display: 'flex', gap: 10 }}>
          {ACCENT_OPTIONS.map((col) => {
            const sel = (c.accent || '#1f6feb').toLowerCase() === col.toLowerCase();
            return (
              <Pressable key={col} onClick={() => set({ accent: col })} scale={0.88}>
                <div style={{
                  width: 32, height: 32, borderRadius: 16, background: col,
                  border: sel ? `2.5px solid ${t.text}` : `2.5px solid transparent`,
                  boxShadow: '0 1px 3px rgba(0,0,0,0.2)'
                }} />
              </Pressable>);

          })}
        </div>
      </div>

      <GroupLabel t={t}>Rechnungs-Fußzeile</GroupLabel>
      <div style={{ padding: '0 16px' }}>
        <textarea value={c.footer || ''} onChange={(e) => set({ footer: e.target.value })}
        rows={3}
        placeholder="Vielen Dank für Ihren Auftrag…"
        style={{
          width: '100%', padding: '12px 14px', borderRadius: 12,
          border: `0.5px solid ${t.inputBorder}`, background: t.card,
          fontSize: 14, color: t.text, outline: 'none', fontFamily: 'inherit',
          resize: 'vertical', lineHeight: 1.45, boxSizing: 'border-box',
          boxShadow: t.shadowCard
        }} />
        <div style={{ fontSize: 12, color: t.textSec, marginTop: 6, lineHeight: 1.4 }}>
          Erscheint unter jeder generierten Rechnung.
        </div>
      </div>

      <div style={{ height: 20 }} />
    </div>);

}

// ─────────────────────────────────────────────────────────────
// Erinnerungen — push toggles + lead-time days
// ─────────────────────────────────────────────────────────────
function ErinnerungenView({ t, c, set, onBack, onClose }) {
  const rContract = c.remContractEnd || { on: true, days: 3 };
  const rReturn = c.remReturnOverdue || { on: true };
  const rMaint = c.remMaintDue || { on: true };
  const rInvoice = c.remInvoiceOverdue || { on: true, days: 7 };
  const rStart = c.remRentalStart || { on: true, days: 1 };
  const rPickup = c.remPickupTime || { on: true, hours: 2 };

  const tagePill = (val, onChange) =>
  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <NumberPill t={t} value={val ?? ''} onChange={(v) => onChange(v === '' ? 0 : v)} />
      <span style={{ fontSize: 13, color: t.textSec, minWidth: 32 }}>Tage</span>
    </div>;
  const stundenPill = (val, onChange) =>
  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <NumberPill t={t} value={val ?? ''} onChange={(v) => onChange(v === '' ? 0 : v)} />
      <span style={{ fontSize: 13, color: t.textSec, minWidth: 32 }}>Std.</span>
    </div>;


  return (
    <div>
      <SubHeader title="Erinnerungen" onBack={onBack} onClose={onClose} t={t} />

      <GroupLabel t={t}>Push-Benachrichtigungen</GroupLabel>
      <HintLine t={t}>System-Mitteilungen, wenn etwas zu tun ist.</HintLine>

      <div style={{ height: 8 }} />
      <GroupCard t={t}>
        <ListRow t={t}
        title="Vor Mietbeginn"
        sub={`Vorlauf: ${rStart.days || 0} Tag${rStart.days === 1 ? '' : 'e'} vor dem Mietstart.`}
        right={
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              {tagePill(rStart.days, (v) => set({ remRentalStart: { ...rStart, days: v } }))}
              <Toggle t={t} on={!!rStart.on} onChange={(v) => set({ remRentalStart: { ...rStart, on: v } })} />
            </div>
        } />

        <ListRow t={t}
        title="Vor Treffpunkt / Abholung"
        sub={`Erinnerung ${rPickup.hours || 0} Stunde${rPickup.hours === 1 ? '' : 'n'} vor der vereinbarten Abholzeit.`}
        right={
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              {stundenPill(rPickup.hours, (v) => set({ remPickupTime: { ...rPickup, hours: v } }))}
              <Toggle t={t} on={!!rPickup.on} onChange={(v) => set({ remPickupTime: { ...rPickup, on: v } })} />
            </div>
        } />

        <ListRow t={t}
        title="Vertrag läuft bald ab"
        sub={`Vorlauf: ${rContract.days || 0} Tag${rContract.days === 1 ? '' : 'e'} vor Mietende.`}
        right={
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              {tagePill(rContract.days, (v) => set({ remContractEnd: { ...rContract, days: v } }))}
              <Toggle t={t} on={!!rContract.on} onChange={(v) => set({ remContractEnd: { ...rContract, on: v } })} />
            </div>
        } />
        
        <ListRow t={t}
        title="Rückgabe überfällig"
        sub="Sofortige Erinnerung, wenn ein Vorgang nicht zurückgegeben wurde."
        right={<Toggle t={t} on={!!rReturn.on} onChange={(v) => set({ remReturnOverdue: { ...rReturn, on: v } })} />} />
        
        <ListRow t={t}
        title="Wartung fällig"
        sub="Erinnerung wenn ein Gerät seinen Wartungstermin erreicht."
        right={<Toggle t={t} on={!!rMaint.on} onChange={(v) => set({ remMaintDue: { ...rMaint, on: v } })} />} />
        
        <ListRow t={t} last
        title="Rechnung überfällig"
        sub={`Erinnerung ${rInvoice.days || 0} Tag${rInvoice.days === 1 ? '' : 'e'} nach Zahlungsfrist.`}
        right={
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              {tagePill(rInvoice.days, (v) => set({ remInvoiceOverdue: { ...rInvoice, days: v } }))}
              <Toggle t={t} on={!!rInvoice.on} onChange={(v) => set({ remInvoiceOverdue: { ...rInvoice, on: v } })} />
            </div>
        } />
        
      </GroupCard>

      <div style={{ height: 16 }} />
    </div>);

}

// ─────────────────────────────────────────────────────────────
// Darstellung — light/dark mode + about
// ─────────────────────────────────────────────────────────────
function DarstellungView({ t, dark, toggleDark, themeId, setThemeId, accents, setAccents, navLayout, setNavLayout, navLabels, setNavLabels, c, set, onBack, onClose }) {
  const useLogoIcon = !!(c && c.useLogoIcon);
  const hasLogo = !!(c && c.logo);
  const THEMES = window.THEMES || {};
  const META = window.THEME_META || [];
  const curId = themeId || (dark ? 'dark' : 'light');
  const curBase = THEMES[curId] || {};
  const curAccent = (accents && accents[curId]) || curBase.accent;

  // A small theme preview swatch (background + card + accent dot).
  const ThemeCard = ({ id, label }) => {
    const th = THEMES[id] || {};
    const on = curId === id;
    const ac = (accents && accents[id]) || th.accent;
    return (
      <Pressable onClick={() => setThemeId && setThemeId(id)} scale={0.96}>
        <div style={{
          borderRadius: 16, overflow: 'hidden', cursor: 'pointer',
          border: `2px solid ${on ? (t.accent) : 'transparent'}`,
          boxShadow: t.shadowCard, background: t.card
        }}>
          <div style={{ height: 64, background: th.bgGradient || th.bg, position: 'relative', padding: 8 }}>
            <div style={{ width: '70%', height: 14, borderRadius: 5, background: th.card, boxShadow: '0 1px 2px rgba(0,0,0,0.08)' }} />
            <div style={{ width: '46%', height: 9, borderRadius: 4, background: th.card, opacity: 0.7, marginTop: 5 }} />
            <div style={{ position: 'absolute', right: 8, bottom: 8, width: 18, height: 18, borderRadius: 9, background: ac }} />
          </div>
          <div style={{ padding: '8px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{label}</span>
            {on && <Icon d={EINST_ICONS.check || 'M5 12l5 5L20 7'} color={t.accent} size={15} sw={2.6} />}
          </div>
        </div>
      </Pressable>);
  };

  const LAYOUTS = [
    { id: 'classic', label: 'Automatisch', sub: 'Passt sich dem Design an (Studio = Vollleiste)' },
    { id: 'pill', label: 'Schwebeleiste', sub: 'Schwebende Pille unten — frei über dem Inhalt' },
    { id: 'bar', label: 'Vollleiste', sub: 'Durchgehende Leiste unten mit Beschriftung' },
    { id: 'command', label: 'Befehlsleiste', sub: 'Suchfeld + Schnell-Plus, minimale Wechsel' },
    { id: 'launcher', label: 'Launcher', sub: 'Ein Knopf öffnet alle Bereiche & Aktionen' }];


  return (
    <div>
      <SubHeader title="Darstellung" onBack={onBack} onClose={onClose} t={t} />

      <GroupLabel t={t}>Design</GroupLabel>
      <div style={{ padding: '0 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {META.map((m) => <ThemeCard key={m.id} id={m.id} label={m.label} />)}
      </div>

      <GroupLabel t={t}>Akzentfarbe</GroupLabel>
      <GroupCard t={t}>
        <div style={{ padding: '14px 16px', display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
          {(curBase.accents || []).map((col) => {
            const on = curAccent === col;
            return (
              <Pressable key={col} onClick={() => setAccents && setAccents({ ...accents, [curId]: col })} scale={0.9}>
                <div style={{
                  width: 32, height: 32, borderRadius: 16, background: col,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  boxShadow: on ? `0 0 0 2px ${t.card}, 0 0 0 4px ${col}` : 'none',
                  cursor: 'pointer'
                }}>
                  {on && <Icon d="M5 12l5 5L20 7" color="#fff" size={16} sw={2.8} />}
                </div>
              </Pressable>);
          })}
          {(() => {
            const presets = curBase.accents || [];
            const isCustom = curAccent && !presets.some((col) => col.toLowerCase() === curAccent.toLowerCase());
            return (
              <label style={{ cursor: 'pointer' }} title="Eigene Farbe wählen">
                <div style={{
                  width: 32, height: 32, borderRadius: 16, position: 'relative', overflow: 'hidden',
                  background: isCustom ? curAccent : 'conic-gradient(from 0deg, #FF3B30, #FF9500, #FFCC00, #34C759, #007AFF, #AF52DE, #FF3B30)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  boxShadow: isCustom ? `0 0 0 2px ${t.card}, 0 0 0 4px ${curAccent}` : 'none'
                }}>
                  {isCustom
                    ? <Icon d="M5 12l5 5L20 7" color="#fff" size={16} sw={2.8} />
                    : <div style={{ width: 14, height: 14, borderRadius: 7, background: t.card }} />}
                  <input type="color" value={curAccent}
                    onChange={(e) => setAccents && setAccents({ ...accents, [curId]: e.target.value })}
                    style={{ position: 'absolute', inset: 0, opacity: 0, cursor: 'pointer' }} />
                </div>
              </label>);
          })()}
        </div>
      </GroupCard>

      <GroupLabel t={t}>Bedienung & Layout</GroupLabel>
      <GroupCard t={t}>
        {LAYOUTS.map((l, i) => {
          const on = (navLayout || 'classic') === l.id;
          return (
            <Pressable key={l.id} onClick={() => setNavLayout && setNavLayout(l.id)} scale={0.99}>
              <div style={{ padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: i < LAYOUTS.length - 1 ? `0.5px solid ${t.sep}` : 'none' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{l.label}</div>
                  <div style={{ fontSize: 12, color: t.textSec, marginTop: 1 }}>{l.sub}</div>
                </div>
                <div style={{
                  width: 22, height: 22, borderRadius: 11, flexShrink: 0,
                  border: on ? `7px solid ${t.accent}` : `2px solid ${t.textTer}`,
                  transition: 'border 0.15s'
                }} />
              </div>
            </Pressable>);
        })}
      </GroupCard>

      <div style={{ height: 18 }} />
      <GroupCard t={t}>
        <ListRow t={t} last
          title="Nur Symbole in der Leiste"
          sub="Beschriftung unter den Icons ausblenden (nur bei Voll- & Automatik-Leiste)"
          right={<Toggle on={navLabels === false} t={t} onChange={(v) => setNavLabels && setNavLabels(!v)} />} />
      </GroupCard>

      <GroupLabel t={t}>Symbol oben rechts</GroupLabel>
      <GroupCard t={t}>
        <ListRow t={t} last={!hasLogo || !useLogoIcon}
        title="Firmenlogo statt Zahnrad"
        sub={hasLogo ?
        'Zeigt dein Logo überall anstelle des Einstellungs‑Icons an.' :
        'Lade zuerst in ‚Stammdaten → Firmenlogo‘ ein Logo hoch.'}
        right={
        <Toggle on={useLogoIcon && hasLogo} t={t}
        onChange={(v) => {if (!hasLogo) return;set({ useLogoIcon: v });}} />
        } />
        
        {useLogoIcon && hasLogo &&
        <div style={{ padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12, borderTop: `0.5px solid ${t.sep}` }}>
            <span style={{ fontSize: 13, color: t.textSec }}>Vorschau:</span>
            <div style={{
            width: 38, height: 38, borderRadius: 19, background: t.card,
            border: `0.5px solid ${t.dark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.06)'}`,
            boxShadow: t.shadowCard,
            display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden'
          }}>
              <img src={c.logo} alt="" style={{ width: 26, height: 26, objectFit: 'contain' }} />
            </div>
          </div>
        }
      </GroupCard>

      <div style={{ height: 16 }} />
    </div>);

}

// ─── Tab-Einstellungen — per-area display & calculation prefs ───
function TabDisplayView({ t, tabSettings, setTabSettings, onBack, onClose }) {
  const cfg = (tab) => (tabSettings && tabSettings[tab]) || {};
  const setCfg = (tab, patch) => setTabSettings && setTabSettings((prev) => ({ ...prev, [tab]: { ...((prev && prev[tab]) || {}), ...patch } }));

  const Segmented = ({ value, options, onPick }) => (
    <div style={{ display: 'flex', gap: 3, padding: 3, borderRadius: 10, background: t.chipStrong }}>
      {options.map(([id, label]) => {
        const on = value === id;
        return (
          <Pressable key={id} onClick={() => onPick(id)} scale={0.96} style={{ flex: 1 }}>
            <div style={{ padding: '7px 10px', textAlign: 'center', borderRadius: 8, fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', background: on ? (t.dark ? '#48484A' : '#fff') : 'transparent', color: on ? t.text : t.textSec, boxShadow: on ? '0 1px 2px rgba(0,0,0,0.08)' : 'none' }}>{label}</div>
          </Pressable>
        );
      })}
    </div>
  );

  const eq = cfg('equipment');
  const zub = cfg('zubehoer');
  const rentalsCfg = cfg('rentals');

  return (
    <div>
      <SubHeader title="Tab-Einstellungen" onBack={onBack} onClose={onClose} t={t} />
      <div style={{ padding: '0 20px 10px', fontSize: 12.5, color: t.textSec, lineHeight: 1.5 }}>
        Lege je Bereich fest, wie Inhalte dargestellt und berechnet werden. Die Einstellungen bleiben gespeichert.
      </div>

      <GroupLabel t={t}>Equipment</GroupLabel>
      <GroupCard t={t}>
        <div style={{ padding: '12px 16px', borderBottom: `0.5px solid ${t.sep}` }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text, marginBottom: 8 }}>Listenansicht</div>
          <Segmented value={eq.view || 'card'} options={[['card', 'Karten'], ['compact', 'Kompakt'], ['table', 'Tabelle']]} onPick={(v) => setCfg('equipment', { view: v })} />
        </div>
        <ListRow t={t} last title="Symbole anzeigen" sub="Produkt-Icons in der Liste ein- oder ausblenden"
          right={<Toggle on={eq.showIcons !== false} t={t} onChange={(v) => setCfg('equipment', { showIcons: v })} />} />
      </GroupCard>

      <GroupLabel t={t}>Zubehör</GroupLabel>
      <GroupCard t={t}>
        <div style={{ padding: '12px 16px', borderBottom: `0.5px solid ${t.sep}` }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text, marginBottom: 8 }}>Listenansicht</div>
          <Segmented value={zub.view || 'card'} options={[['card', 'Karten'], ['compact', 'Kompakt'], ['table', 'Tabelle']]} onPick={(v) => setCfg('zubehoer', { view: v })} />
        </div>
        <ListRow t={t} last title="Symbole anzeigen" sub="Kategorie-Icons ein- oder ausblenden"
          right={<Toggle on={zub.showIcons !== false} t={t} onChange={(v) => setCfg('zubehoer', { showIcons: v })} />} />
      </GroupCard>

      <GroupLabel t={t}>Mietvertrag</GroupLabel>
      <GroupCard t={t}>
        <div style={{ padding: '12px 16px', borderBottom: `0.5px solid ${t.sep}` }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text, marginBottom: 8 }}>Formular-Darstellung</div>
          <Segmented value={rentalsCfg.layout || 'sections'} options={[['sections', 'Abschnitte'], ['accordion', 'Aufklappbar']]} onPick={(v) => setCfg('rentals', { layout: v })} />
        </div>
        <ListRow t={t} last title="Kontakt standardmäßig ausklappen" sub="Adresse & Kontakt beim Öffnen sofort zeigen"
          right={<Toggle on={!!rentalsCfg.expandContact} t={t} onChange={(v) => setCfg('rentals', { expandContact: v })} />} />
      </GroupCard>

      <div style={{ height: 16 }} />
    </div>
  );
}

Object.assign(window, {
  DokumenteSettingsView, ErinnerungenView, DarstellungView, TabDisplayView
});