// Einstellungen — multi-section settings sheet for the RentFlow mobile app.
// Sections: Stammdaten, Bank & Steuer, Logistik, Dokumente, Erinnerungen, Darstellung.

const { useState: useStateEinst, useEffect: useEffectEinst, useRef: useRefEinst } = React;

// ─────────────────────────────────────────────────────────────
// Section icons (stroke paths for the Icon component)
// ─────────────────────────────────────────────────────────────
const EINST_ICONS = {
  building: 'M3 21h18 M5 21V8l7-5 7 5v13 M9 21v-6h6v6 M9 9.5h.01 M15 9.5h.01 M9 12.5h.01 M15 12.5h.01',
  euro:     'M18 7a6 6 0 00-9 0M18 17a6 6 0 01-9 0M5 10h10M5 14h10',
  truck:    'M3 16h2m14 0h2M5 16a2 2 0 104 0M15 16a2 2 0 104 0M3 16V8a1 1 0 011-1h11v9M15 9h3.6a1 1 0 01.83.45L21 12v4',
  doc:      'M6 2h8l6 6v12a2 2 0 01-2 2H6a2 2 0 01-2-2V4a2 2 0 012-2zM14 2v6h6M9 14h6M9 18h4',
  bell:     'M12 2a6 6 0 016 6v4l2 3H4l2-3V8a6 6 0 016-6zM10 19a2 2 0 004 0',
  moon:     'M21 12.8A9 9 0 1111.2 3a7 7 0 009.8 9.8z',
  sun:      'M12 5V3M12 21v-2M5 12H3M21 12h-2M5.6 5.6L4.2 4.2M19.8 19.8l-1.4-1.4M5.6 18.4L4.2 19.8M19.8 4.2l-1.4 1.4M12 8a4 4 0 100 8 4 4 0 000-8z',
  camera:   'M4 8a2 2 0 012-2h2l2-2h4l2 2h2a2 2 0 012 2v10a2 2 0 01-2 2H6a2 2 0 01-2-2V8zM12 17a4 4 0 100-8 4 4 0 000 8z',
  backup:   'M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4 M7 10l5 5 5-5 M12 15V3',
};

// ─────────────────────────────────────────────────────────────
// Main sheet — wraps Sheet primitive and routes between list / sub-views
// ─────────────────────────────────────────────────────────────
function FirmenprofilSheet({ open, onClose, company, setCompany, toast, logistik, setLogistik, dark, toggleDark }) {
  const t = useTheme();
  const [sub, setSub] = useStateEinst(null);
  useEffectEinst(() => { if (!open) { const id = setTimeout(() => setSub(null), 320); return () => clearTimeout(id); } }, [open]);

  const c = { ...DEFAULT_COMPANY, ...(company || {}) };
  const set = (patch) => setCompany(prev => {
    const next = { ...DEFAULT_COMPANY, ...prev, ...patch };
    // keep legacy `address` in sync if street/cityPostal changed
    if ('street' in patch || 'cityPostal' in patch) {
      next.address = [next.street, next.cityPostal].filter(Boolean).join('\n');
    }
    return next;
  });

  const l = { ...(window.DEFAULT_LOGISTIK || {}), ...(logistik || {}) };
  const setL = (patch) => setLogistik && setLogistik(prev => ({ ...prev, ...patch }));

  let body;
  if (sub === 'stamm')  body = <StammdatenView t={t} c={c} set={set} onBack={() => setSub(null)} onClose={onClose} toast={toast}/>;
  else if (sub === 'bank')  body = <BankSteuerView t={t} c={c} set={set} onBack={() => setSub(null)} onClose={onClose}/>;
  else if (sub === 'log')   body = <LogistikSettingsView t={t} l={l} setL={setL} onBack={() => setSub(null)} onClose={onClose}/>;
  else if (sub === 'dok')   body = <DokumenteSettingsView t={t} c={c} set={set} onBack={() => setSub(null)} onClose={onClose}/>;
  else if (sub === 'rem')   body = <ErinnerungenView t={t} c={c} set={set} onBack={() => setSub(null)} onClose={onClose}/>;
  else if (sub === 'bkp')   body = <BackupView t={t} onBack={() => setSub(null)} onClose={onClose} toast={toast}/>;
  else if (sub === 'darst') body = <DarstellungView t={t} dark={dark} toggleDark={toggleDark} c={c} set={set} onBack={() => setSub(null)} onClose={onClose}/>;
  else                      body = <SettingsList t={t} c={c} onPick={setSub} onClose={onClose}/>;

  return (
    <Sheet open={open} onClose={onClose} maxHeight="92%">
      <div style={{ paddingBottom: 16 }}>{body}</div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────
// Top-level list view
// ─────────────────────────────────────────────────────────────
function SettingsList({ t, c, onPick, onClose }) {
  const sections = [
    { id: 'stamm', icon: EINST_ICONS.building, color: '#007AFF', title: 'Stammdaten',    sub: 'Firma & Kontakt' },
    { id: 'bank',  icon: EINST_ICONS.euro,     color: '#34C759', title: 'Bank & Steuer', sub: 'IBAN, USt, MwSt.' },
    { id: 'log',   icon: EINST_ICONS.truck,    color: '#FF9500', title: 'Logistik',      sub: 'Lager & km-Sätze' },
    { id: 'dok',   icon: EINST_ICONS.doc,      color: '#AF52DE', title: 'Dokumente',     sub: 'Nummern & Fristen' },
    { id: 'rem',   icon: EINST_ICONS.bell,     color: '#FF3B30', title: 'Erinnerungen',  sub: 'Push & Vorlauf' },
    { id: 'bkp',   icon: EINST_ICONS.backup,   color: '#00A39C', title: 'Datensicherung', sub: 'Export & Import' },
    { id: 'darst', icon: EINST_ICONS.moon,     color: '#5856D6', title: 'Darstellung',   sub: 'Hell · Dunkel' },
  ];

  return (
    <div>
      {/* Header with title + Fertig */}
      <div style={{ padding: '4px 20px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div>
          <div style={{ fontSize: 26, fontWeight: 700, color: t.text, letterSpacing: -0.6 }}>Einstellungen</div>
          <div style={{ fontSize: 13, color: t.textSec, marginTop: 2 }}>Firma, Logistik & App-Verhalten</div>
        </div>
        <Pressable onClick={onClose} scale={0.9}>
          <div style={{ fontSize: 15, color: t.accent, fontWeight: 600 }}>Fertig</div>
        </Pressable>
      </div>

      {/* Firmen-Header-Karte */}
      <div style={{ padding: '14px 16px 4px' }}>
        <div style={{
          background: t.card, borderRadius: 16, padding: 14,
          display: 'flex', alignItems: 'center', gap: 12,
          boxShadow: t.shadowCard,
        }}>
          <div style={{
            width: 52, height: 52, borderRadius: 12, flexShrink: 0,
            background: c.logo ? '#fff' : '#007AFF',
            display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden',
            border: c.logo ? `1px solid ${t.sep}` : 'none',
          }}>
            {c.logo
              ? <img src={c.logo} alt="" style={{ maxWidth: '88%', maxHeight: '88%', objectFit: 'contain' }}/>
              : <Icon d={EINST_ICONS.building} color="#fff" size={26} sw={1.6}/>}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: -0.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.name}</div>
            <div style={{ fontSize: 13, color: t.textSec, marginTop: 2 }}>{c.owner || c.tagline || '—'}</div>
          </div>
        </div>
      </div>

      {/* Section rows */}
      <div style={{ padding: '14px 16px 0' }}>
        <div style={{ background: t.card, borderRadius: 14, overflow: 'hidden', boxShadow: t.shadowCard }}>
          {sections.map((s, i) => (
            <Pressable key={s.id} onClick={() => onPick(s.id)} scale={0.995}>
              <div style={{
                padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12,
                borderBottom: i < sections.length - 1 ? `0.5px solid ${t.sep}` : 'none',
              }}>
                <div style={{
                  width: 34, height: 34, borderRadius: 9, background: s.color + '22',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <Icon d={s.icon} color={s.color} size={19} sw={1.9}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: t.text, letterSpacing: -0.15 }}>{s.title}</div>
                  <div style={{ fontSize: 12, color: t.textSec, marginTop: 1 }}>{s.sub}</div>
                </div>
                <Icon d={icons.chev} color={t.textTer} size={15} sw={2.2}/>
              </div>
            </Pressable>
          ))}
        </div>
      </div>

      {/* About strip */}
      <div style={{ padding: '22px 24px 4px', textAlign: 'center', fontSize: 12.5, color: t.textSec, lineHeight: 1.5 }}>
        <strong style={{ color: t.text }}>RentFlow Manager</strong> · Mobile-Edition für iOS.<br />
        Verwaltung von Vermietungen, Equipment, Terminen und Finanzen — synchron zur Desktop-App.
        <div style={{ marginTop: 8, fontSize: 11, color: t.textTer, fontVariantNumeric: 'tabular-nums' }}>Version 1.1.0 (build 12)</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Stammdaten — logo, contact, register & tax IDs
// ─────────────────────────────────────────────────────────────
function StammdatenView({ t, c, set, onBack, onClose, toast }) {
  const fileRef = useRefEinst(null);
  const onLogo = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    fileToScaledDataURL(f, 480, (url) => {
      if (url) { set({ logo: url }); toast && toast('Logo hochgeladen'); }
      else toast && toast('Bild konnte nicht geladen werden');
    });
  };

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

      {/* Logo card */}
      <GroupLabel t={t}>Logo & Identität</GroupLabel>
      <GroupCard t={t}>
        <div style={{ padding: '14px 14px', display: 'flex', gap: 12, alignItems: 'center' }}>
          <div style={{
            width: 60, height: 60, borderRadius: 14, background: c.logo ? '#fff' : '#007AFF',
            flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden',
            border: c.logo ? `1px solid ${t.sep}` : 'none',
          }}>
            {c.logo
              ? <img src={c.logo} alt="" style={{ maxWidth: '88%', maxHeight: '88%', objectFit: 'contain' }}/>
              : <Icon d={EINST_ICONS.building} color="#fff" size={30} sw={1.6}/>}
          </div>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
            <Pressable onClick={() => fileRef.current && fileRef.current.click()} scale={0.97}>
              <div style={{
                padding: '8px 0', textAlign: 'center', borderRadius: 9,
                background: t.solidBg, color: t.solidFg, fontSize: 13, fontWeight: 600,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              }}>
                <Icon d={EINST_ICONS.camera} color={t.solidFg} size={14} sw={2}/>
                {c.logo ? 'Logo ersetzen' : 'Logo hochladen'}
              </div>
            </Pressable>
            {c.logo && (
              <Pressable onClick={() => set({ logo: '' })} scale={0.97}>
                <div style={{ padding: '7px 0', textAlign: 'center', borderRadius: 9, background: t.redSoft, color: t.red, fontSize: 12, fontWeight: 600 }}>Entfernen</div>
              </Pressable>
            )}
          </div>
          <input ref={fileRef} type="file" accept="image/*" onChange={onLogo} style={{ display: 'none' }}/>
        </div>
        <InputRow label="Firmenname" value={c.name} onChange={v => set({ name: v })} t={t}/>
        <InputRow label="Inhaber"    value={c.owner} onChange={v => set({ owner: v })} t={t}/>
        <InputRow label="Zusatz / Slogan" value={c.tagline} onChange={v => set({ tagline: v })} placeholder="z.B. Vermietung Tontechnik" t={t} last/>
      </GroupCard>

      {/* Adresse */}
      <GroupLabel t={t}>Anschrift</GroupLabel>
      <GroupCard t={t}>
        <InputRow label="Strasse"    value={c.street}     onChange={v => set({ street: v })}     placeholder="Musterstraße 12" t={t}/>
        <InputRow label="PLZ & Ort"  value={c.cityPostal} onChange={v => set({ cityPostal: v })} placeholder="80331 München"   t={t} last/>
      </GroupCard>

      {/* Kontakt */}
      <GroupLabel t={t}>Kontakt</GroupLabel>
      <GroupCard t={t}>
        <InputRow label="E-Mail"  value={c.email} onChange={v => set({ email: v })} type="email" t={t}/>
        <InputRow label="Telefon" value={c.phone} onChange={v => set({ phone: v })} type="tel"   t={t}/>
        <InputRow label="Website" value={c.web}   onChange={v => set({ web: v })}   placeholder="www.…" t={t} last/>
      </GroupCard>

      {/* Steuer-IDs */}
      <GroupLabel t={t}>Register & Steuer-IDs</GroupLabel>
      <GroupCard t={t}>
        <InputRow label="Steuernummer" value={c.taxId} onChange={v => set({ taxId: v })} placeholder="143/256/12345" hint="Vom Finanzamt vergeben." t={t}/>
        <InputRow label="USt-IdNr."    value={c.vatId} onChange={v => set({ vatId: v })} placeholder="DE123456789"   hint="Für innergem. Lieferungen." t={t}/>
        <InputRow label="Handelsregister-Nr." value={c.hrb} onChange={v => set({ hrb: v })} placeholder="HRB 123456" hint="Nur bei eingetragener Firma." t={t}/>
        <InputRow label="Amtsgericht"  value={c.amtsgericht} onChange={v => set({ amtsgericht: v })} placeholder="München" t={t} last/>
      </GroupCard>

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

// ─────────────────────────────────────────────────────────────
// Bank & Steuer
// ─────────────────────────────────────────────────────────────
function BankSteuerView({ t, c, set, onBack, onClose }) {
  return (
    <div>
      <SubHeader title="Bank & Steuer" onBack={onBack} onClose={onClose} t={t}/>

      <GroupLabel t={t}>Bankverbindung</GroupLabel>
      <GroupCard t={t}>
        <InputRow label="IBAN" value={c.iban} onChange={v => set({ iban: v })} placeholder="DE12 3456 7890 …" t={t}/>
        <InputRow label="BIC"  value={c.bic}  onChange={v => set({ bic: v })}  placeholder="BYLADEM1MUC" t={t}/>
        <InputRow label="Bank" value={c.bank} onChange={v => set({ bank: v })} placeholder="z.B. Sparkasse" t={t} last/>
      </GroupCard>

      <GroupLabel t={t}>Umsatzsteuer</GroupLabel>
      <GroupCard t={t}>
        <ListRow t={t}
          title="Kleinunternehmer (§ 19 UStG)"
          sub="Rechnungen werden ohne MwSt. ausgewiesen."
          right={<Toggle on={!!c.kleinunternehmer} onChange={v => set({ kleinunternehmer: v })} t={t}/>}
        />
        <ListRow t={t} last
          title="Standard-MwSt.-Satz"
          sub={c.kleinunternehmer ? 'Nicht aktiv – Kleinunternehmer.' : 'Vorbelegung auf neuen Rechnungen.'}
          right={
            <Segmented t={t}
              value={c.defaultVat}
              onChange={v => set({ defaultVat: v })}
              options={[
                { value: 19, label: '19 %' },
                { value: 7,  label: '7 %' },
                { value: 0,  label: '0 %' },
              ]}/>
          }
        />
      </GroupCard>
      <div style={{ height: 16 }}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Logistik settings — uses the logistik state
// ─────────────────────────────────────────────────────────────
function LogistikSettingsView({ t, l, setL, onBack, onClose }) {
  const tripOpts = [
    { value: 1, label: '1×' },
    { value: 2, label: '2×' },
    { value: 4, label: '4×' },
  ];
  const factor = (typeof l.tripFactor === 'number') ? l.tripFactor : 4;
  const rate = Number(l.kmRate) || 0;
  const pauschale = Number(l.pauschale) || 0;
  const exampleTotal = (10 * factor * rate + pauschale).toFixed(2).replace('.', ',');

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

      <GroupLabel t={t}>Lager & Startadresse</GroupLabel>
      <GroupCard t={t}>
        <InputRow label="Adresse" value={l.lagerAddress} onChange={v => setL({ lagerAddress: v })}
          placeholder="Bahnhofstr. 18, 82110 Germering"
          hint="Ausgangspunkt für km-Berechnung." t={t} last/>
      </GroupCard>

      <GroupLabel t={t}>Lieferpreise</GroupLabel>
      <GroupCard t={t}>
        <RateEditRow label="Preis pro km" value={l.kmRate} onChange={v => setL({ kmRate: v })} step={0.1} suffix="€/km" t={t}/>
        <RateEditRow label="Pauschale" value={l.pauschale} onChange={v => setL({ pauschale: v })} step={1} suffix="€" t={t}/>
        <ListRow t={t} last
          title="Standard-Fahrten" sub="Hin- & Rückweg für Anlieferung + Abholung."
          right={<Segmented t={t} value={factor}
            onChange={v => setL({ tripFactor: v, returnTrip: v !== 1 })}
            options={tripOpts}/>}
        />
      </GroupCard>

      {/* Live example */}
      <div style={{ padding: '14px 16px 4px' }}>
        <div style={{
          background: t.accentSoft, borderRadius: 12,
          padding: '12px 14px', display: 'flex', gap: 10, alignItems: 'flex-start',
        }}>
          <span style={{ fontSize: 17, lineHeight: 1 }}>💡</span>
          <div style={{ fontSize: 12, color: t.text, lineHeight: 1.5 }}>
            <strong>Beispiel 10 km:</strong> {exampleTotal} €
            <div style={{ color: t.textSec, marginTop: 2 }}>
              {String(rate).replace('.', ',')} €/km × {factor} Fahrten + {pauschale} € Pauschale
            </div>
          </div>
        </div>
      </div>

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

// Hide the placeholder card with the dud control (above) — clean up
// Actually we don't want a duplicate row. Remove the first noisy card by overriding here:
// (kept structure simple by rendering second card only)

function RateEditRow({ label, value, onChange, step = 1, suffix, t }) {
  const [tmp, setTmp] = useStateEinst(String(value ?? '').replace('.', ','));
  useEffectEinst(() => { setTmp(String(value ?? '').replace('.', ',')); }, [value]);
  const commit = () => {
    const n = Number(String(tmp).replace(',', '.'));
    if (!isNaN(n)) onChange(n);
    else setTmp(String(value ?? '').replace('.', ','));
  };
  return (
    <ListRow t={t} title={label} sub={null}
      right={<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <input value={tmp} onChange={e => setTmp(e.target.value)} onBlur={commit}
          onKeyDown={e => { if (e.key === 'Enter') e.target.blur(); }}
          inputMode="decimal"
          style={{
            width: 68, padding: '6px 8px', borderRadius: 8,
            border: `0.5px solid ${t.inputBorder}`, background: t.inputBg,
            fontSize: 14, color: t.text, outline: 'none', fontFamily: 'inherit',
            textAlign: 'right', boxSizing: 'border-box', fontVariantNumeric: 'tabular-nums',
          }}/>
        <span style={{ fontSize: 13, color: t.textSec, minWidth: 32 }}>{suffix}</span>
      </div>}
    />
  );
}

Object.assign(window, {
  FirmenprofilSheet, EINST_ICONS, previewNumber: window.previewNumber,
});
