// Einstellungen sheet — full multi-section settings UI (mobile adaptation).
// Also exports the PDF rendering utilities used elsewhere (buildDocHTML, printDocHTML, TemplatePreview).

const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────
// Defaults
// ─────────────────────────────────────────────────────────────
const DEFAULT_COMPANY = {
  // Stammdaten
  name: '',
  tagline: '',
  owner: '',
  street: '',
  cityPostal: '',
  address: '', // derived, used by buildDocHTML
  phone: '',
  email: '',
  web: '',
  taxId: '',
  vatId: '',
  hrb: '',
  amtsgericht: '',
  // Bank & Steuer
  iban: '',
  bic: '',
  bank: '',
  kleinunternehmer: true,
  defaultVat: 19,
  // Logo + PDF
  logo: '',
  template: 'modern',
  accent: '#1f6feb',
  // Dokumente
  invoicePattern: 'RE-{YYYY}-{####}',
  contractPattern: 'MV-{YYYY}-{####}',
  invoiceCounter: 1,
  paymentDays: 14,
  defaultDeposit: 200,
  footer: 'Vielen Dank für Ihren Auftrag. Zahlbar ohne Abzug innerhalb der Zahlungsfrist.',
  // Erinnerungen
  remContractEnd:    { on: true,  days: 3 },
  remReturnOverdue:  { on: true },
  remMaintDue:       { on: true },
  remInvoiceOverdue: { on: true,  days: 7 },
  remRentalStart:    { on: true,  days: 1 },
  remPickupTime:     { on: true,  hours: 2 },
};

const PDF_TEMPLATES = [
  { id: 'modern',    label: 'Modern',    desc: 'Farbakzent, klare Linien' },
  { id: 'klassisch', label: 'Klassisch', desc: 'Serifen, zentriert' },
  { id: 'minimal',   label: 'Minimal',   desc: 'Schlicht, schwarz-weiß' },
];
const ACCENT_OPTIONS = ['#1f6feb', '#0a7d4d', '#b23b2e', '#6b4bb3', '#1a1a1a', '#c2761a'];

const esc = (s) => String(s == null ? '' : s)
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
const euro = (n) => Number(n || 0).toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';

// ─────────────────────────────────────────────────────────────
// PDF document HTML (used for on-screen preview + print)
// ─────────────────────────────────────────────────────────────
function buildDocHTML(company, doc) {
  const c = { ...DEFAULT_COMPANY, ...(company || {}) };
  // Compose address from split fields if available
  const addrLines = [c.street, c.cityPostal].filter(Boolean);
  const addr = addrLines.length ? addrLines.join('\n') : (c.address || '');
  const tpl = c.template || 'modern';
  const logo = c.logo
    ? `<img class="pd-logo" src="${c.logo}" alt="Logo"/>`
    : `<div class="pd-co-name">${esc(c.name)}</div>${c.tagline ? `<div class="pd-co-sub">${esc(c.tagline)}</div>` : ''}`;

  const contactLine = [c.phone, c.email, c.web].filter(Boolean).map(esc).join('  ·  ');
  const legalLine = [
    c.taxId ? 'St.-Nr.: ' + esc(c.taxId) : '',
    c.vatId ? 'USt-IdNr.: ' + esc(c.vatId) : '',
    c.hrb   ? esc(c.hrb)   : '',
  ].filter(Boolean).join('  ·  ');
  const bankLine = [
    c.bank ? esc(c.bank) : '',
    c.iban ? 'IBAN: ' + esc(c.iban) : '',
    c.bic  ? 'BIC: '  + esc(c.bic)  : '',
  ].filter(Boolean).join('  ·  ');

  const head = `
    <div class="pd-head">
      <div class="pd-co">${logo}${c.logo && c.tagline ? `<div class="pd-co-sub" style="margin-top:.5em">${esc(c.tagline)}</div>` : ''}</div>
      <div class="pd-meta">
        ${doc.number ? `<div class="pd-docno">${esc(doc.number)}</div>` : ''}
        <div>${esc(doc.date || '')}</div>
      </div>
    </div>`;

  const recipient = (doc.tenantName || doc.address) ? `
    <div class="pd-addr-block">
      <div class="pd-addr-label">Empfänger</div>
      <div><strong>${esc(doc.tenantName || '')}</strong></div>
      <div>${esc(doc.address || '')}</div>
    </div>` : '';

  let middle = '';
  if (doc.kind === 'invoice' && doc.invoice) {
    const iv = doc.invoice;
    const rows = (iv.items || []).map(it => `
      <tr>
        <td>${esc(it.desc)}${it.sub ? `<div class="pd-sub">${esc(it.sub)}</div>` : ''}</td>
        <td class="num">${esc(it.qty)}</td>
        <td class="num">${euro(it.unit)}</td>
        <td class="num">${euro(it.sum)}</td>
      </tr>`).join('');
    const showTax = !c.kleinunternehmer;
    middle = `
      <table class="pd-items">
        <thead><tr><th>Beschreibung</th><th class="num">Menge</th><th class="num">Einzel</th><th class="num">Summe</th></tr></thead>
        <tbody>${rows}</tbody>
      </table>
      <div class="pd-totals">
        <div class="row muted"><span>Zwischensumme</span><span class="pd-val">${euro(iv.subtotal)}</span></div>
        ${iv.discount > 0 ? `<div class="row disc"><span>Rabatt</span><span class="pd-val">− ${euro(iv.discount)}</span></div>` : ''}
        ${showTax ? `<div class="row muted"><span>Nettobetrag</span><span class="pd-val">${euro(iv.net)}</span></div>
        <div class="row muted"><span>zzgl. ${c.defaultVat || 19} % MwSt.</span><span class="pd-val">${euro(iv.tax)}</span></div>` : ''}
        <div class="grand"><span>Gesamtbetrag</span><span class="pd-val">${euro(iv.total)}</span></div>
        ${!showTax ? `<div class="row muted" style="margin-top:.4em;font-size:.85em">Kein Ausweis der USt. gemäß § 19 UStG (Kleinunternehmerregelung).</div>` : ''}
      </div>
      <div class="pd-foot">
        <div>Zahlungsziel: ${c.paymentDays || 14} Tage netto.${c.footer ? '  ' + esc(c.footer) : ''}</div>
        ${bankLine ? `<div style="margin-top:.5em">${bankLine}</div>` : ''}
      </div>`;
  } else {
    middle = `<div class="pd-body">${esc(doc.bodyText != null ? doc.bodyText : doc.text || '')}</div>`;
    if (doc.signature) {
      middle += `
        <div class="pd-sign">
          <div class="pd-sign-box"><div class="pd-sign-line">Ort, Datum</div></div>
          <div class="pd-sign-box"><div class="pd-sign-line">Unterschrift Mieter</div></div>
          <div class="pd-sign-box"><div class="pd-sign-line">Unterschrift Vermieter</div></div>
        </div>`;
    }
  }

  const title = doc.kind === 'invoice' ? 'Rechnung' : (doc.title || 'Dokument');
  const footerContact = `
    <div class="pd-foot">
      <div class="cols">
        <div>${esc(c.name)}${addr ? '<br/>' + esc(addr).replaceAll('\n', '<br/>') : ''}</div>
        <div>${contactLine ? contactLine + '<br/>' : ''}${legalLine}</div>
      </div>
    </div>`;

  return `<div class="pdfdoc tpl-${tpl}" style="--accent:${esc(c.accent || '#1f6feb')}">
    ${tpl === 'modern' ? '<div class="pd-accentbar"></div>' : ''}
    ${head}
    <h1 class="pd-title">${esc(title)}</h1>
    ${recipient}
    ${middle}
    ${doc.kind === 'invoice' ? footerContact : ''}
  </div>`;
}

function printDocHTML(html) {
  const root = document.getElementById('print-root');
  if (!root) return;
  root.innerHTML = `<div style="font-size:11pt;max-width:180mm;margin:0 auto">${html}</div>`;
  const done = () => { root.innerHTML = ''; window.removeEventListener('afterprint', done); };
  window.addEventListener('afterprint', done);
  setTimeout(() => window.print(), 60);
}

function fileToScaledDataURL(file, maxDim, cb) {
  const reader = new FileReader();
  reader.onload = (e) => {
    const img = new Image();
    img.onload = () => {
      let { width, height } = img;
      const scale = Math.min(1, maxDim / Math.max(width, height));
      width = Math.round(width * scale); height = Math.round(height * scale);
      const cv = document.createElement('canvas');
      cv.width = width; cv.height = height;
      const ctx = cv.getContext('2d');
      ctx.drawImage(img, 0, 0, width, height);
      cb(cv.toDataURL('image/png'));
    };
    img.onerror = () => cb('');
    img.src = e.target.result;
  };
  reader.onerror = () => cb('');
  reader.readAsDataURL(file);
}

function TemplatePreview({ company, scale = 0.42 }) {
  const sampleDoc = {
    kind: 'invoice', number: 'RE-2026-118', date: '01.06.2026',
    tenantName: 'Lena Wagner', address: 'Seestr. 9\n82211 Herrsching',
    invoice: {
      items: [{ desc: 'JBL EON 712 (Aktivlautsprecher)', sub: '13.06.–14.06.2026', qty: '2 Tage', unit: 45, sum: 90 }],
      subtotal: 90, discount: 10, net: 67.23, tax: 12.77, total: 80,
    },
  };
  const html = buildDocHTML(company, sampleDoc);
  return (
    <div style={{ borderRadius: 12, overflow: 'hidden', border: '1px solid rgba(0,0,0,0.08)', background: '#fff', height: 360 }}>
      <div style={{ width: 794, padding: 28, transform: `scale(${scale})`, transformOrigin: 'top left' }}
           dangerouslySetInnerHTML={{ __html: html }}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Shared UI primitives for the settings sheet
// ─────────────────────────────────────────────────────────────
function SubHeader({ title, onBack, onClose, t }) {
  return (
    <div style={{
      position: 'sticky', top: 20, zIndex: 3, background: t.sheetBg,
      padding: '6px 16px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      borderBottom: `0.5px solid ${t.sep}`,
    }}>
      {onBack ? (
        <Pressable onClick={onBack} scale={0.9}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 2, color: t.accent }}>
            <Icon d={icons.back} color={t.accent} size={20} sw={2.4}/>
            <span style={{ fontSize: 15, fontWeight: 500 }}>Einstellungen</span>
          </div>
        </Pressable>
      ) : <div style={{ width: 80 }}/>}
      <div style={{ fontSize: 15, fontWeight: 700, color: t.text, letterSpacing: -0.2 }}>{title}</div>
      <Pressable onClick={onClose} scale={0.9}>
        <div style={{ fontSize: 15, color: t.accent, fontWeight: 600 }}>Fertig</div>
      </Pressable>
    </div>
  );
}

function GroupLabel({ children, t }) {
  return (
    <div style={{
      fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase',
      letterSpacing: 0.6, padding: '20px 20px 8px',
    }}>{children}</div>
  );
}

function GroupCard({ children, t }) {
  return (
    <div style={{
      margin: '0 16px', background: t.card, borderRadius: 14, overflow: 'hidden',
      boxShadow: t.shadowCard,
    }}>{children}</div>
  );
}

function HintLine({ children, t }) {
  return (
    <div style={{ fontSize: 12, color: t.textSec, padding: '8px 20px 0', lineHeight: 1.4 }}>{children}</div>
  );
}

// Plain text/number input row (label above, input below) — inside a GroupCard.
function InputRow({ label, value, onChange, placeholder, type = 'text', suffix, t, hint, last }) {
  return (
    <div style={{ padding: '12px 14px', borderBottom: !last ? `0.5px solid ${t.sep}` : 'none' }}>
      {label && <div style={{
        fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase',
        letterSpacing: 0.5, marginBottom: 6,
      }}>{label}</div>}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <input value={value || ''} onChange={e => onChange(e.target.value)}
          placeholder={placeholder} type={type}
          style={{
            flex: 1, padding: '10px 12px', borderRadius: 10,
            border: `0.5px solid ${t.inputBorder}`, background: t.inputBg,
            fontSize: 14, color: t.text, outline: 'none', fontFamily: 'inherit',
            boxSizing: 'border-box', minWidth: 0,
          }}
        />
        {suffix && <span style={{ fontSize: 13, color: t.textSec, fontWeight: 500 }}>{suffix}</span>}
      </div>
      {hint && <div style={{ fontSize: 11, color: t.textSec, marginTop: 6, lineHeight: 1.35 }}>{hint}</div>}
    </div>
  );
}

// iOS-style switch
function Toggle({ on, onChange, t }) {
  return (
    <Pressable onClick={() => onChange(!on)} scale={0.94}>
      <div style={{
        width: 50, height: 30, borderRadius: 15,
        background: on ? '#34C759' : t.chipStrong,
        position: 'relative', transition: 'background 0.2s',
      }}>
        <div style={{
          position: 'absolute', top: 2, left: on ? 22 : 2,
          width: 26, height: 26, borderRadius: 13, background: '#fff',
          boxShadow: '0 2px 4px rgba(0,0,0,0.2)', transition: 'left 0.2s',
        }}/>
      </div>
    </Pressable>
  );
}

// Row with title + optional subtitle + right-side accessory (toggle / segmented / value)
function ListRow({ title, sub, right, t, last, padding = '12px 14px' }) {
  return (
    <div style={{
      padding, borderBottom: !last ? `0.5px solid ${t.sep}` : 'none',
      display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 500, color: t.text }}>{title}</div>
        {sub && <div style={{ fontSize: 12, color: t.textSec, marginTop: 2, lineHeight: 1.35 }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

// Compact segmented control
function Segmented({ options, value, onChange, t }) {
  return (
    <div style={{
      display: 'inline-flex', padding: 2, borderRadius: 8,
      background: t.chipStrong, gap: 0,
    }}>
      {options.map(o => {
        const sel = o.value === value;
        return (
          <Pressable key={String(o.value)} onClick={() => onChange(o.value)} scale={0.96}>
            <div style={{
              padding: '5px 11px', borderRadius: 6,
              background: sel ? (t.dark ? '#636366' : '#fff') : 'transparent',
              fontSize: 12, fontWeight: 600, color: t.text,
              boxShadow: sel ? '0 1px 2px rgba(0,0,0,0.1)' : 'none',
              minWidth: 28, textAlign: 'center',
            }}>{o.label}</div>
          </Pressable>
        );
      })}
    </div>
  );
}

// Small inline numeric input for "X Tage" right-side accessory
function NumberPill({ value, onChange, t, width = 48 }) {
  return (
    <input value={value} onChange={e => {
      const n = e.target.value.replace(/[^\d]/g, '');
      onChange(n === '' ? '' : Number(n));
    }} inputMode="numeric"
    style={{
      width, padding: '6px 8px', borderRadius: 8,
      border: `0.5px solid ${t.inputBorder}`, background: t.inputBg,
      fontSize: 14, color: t.text, outline: 'none', fontFamily: 'inherit',
      textAlign: 'center', boxSizing: 'border-box', fontVariantNumeric: 'tabular-nums',
    }}/>
  );
}

// Build "next" number from a pattern: replaces {YYYY}, {YY}, {####}, {###}, {##} placeholders.
function previewNumber(pattern, counter = 1) {
  const y = new Date().getFullYear();
  return String(pattern || '')
    .replaceAll('{YYYY}', String(y))
    .replaceAll('{YY}', String(y).slice(-2))
    .replace(/\{(#+)\}/g, (_, hashes) => String(counter).padStart(hashes.length, '0'));
}

Object.assign(window, {
  DEFAULT_COMPANY, PDF_TEMPLATES, ACCENT_OPTIONS, buildDocHTML, printDocHTML,
  fileToScaledDataURL, TemplatePreview, previewNumber, euroFmt: euro,
});
