// Settings page — global app + owner configuration

function SettingsPage({ data }) {
  const { settings, store } = data;
  const [form, setForm] = React.useState(() => ({
    platformName: settings?.platformName || '',
    ownerName: settings?.ownerName || '',
    ownerEmail: settings?.ownerEmail || '',
    ownerPhone: settings?.ownerPhone || '',
    ownerAddress: settings?.ownerAddress || '',
    ownerIban: settings?.ownerIban || '',
    ownerUstId: settings?.ownerUstId || '',
    notes: settings?.notes || '',
  }));
  const [busy, setBusy] = React.useState(false);
  const [savedAt, setSavedAt] = React.useState(null);
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    setForm({
      platformName: settings?.platformName || '',
      ownerName: settings?.ownerName || '',
      ownerEmail: settings?.ownerEmail || '',
      ownerPhone: settings?.ownerPhone || '',
      ownerAddress: settings?.ownerAddress || '',
      ownerIban: settings?.ownerIban || '',
      ownerUstId: settings?.ownerUstId || '',
      notes: settings?.notes || '',
    });
  }, [settings]);

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const save = async (e) => {
    e?.preventDefault();
    setBusy(true); setErr(null);
    try {
      await store.updateSettings({
        platformName: form.platformName.trim() || null,
        ownerName: form.ownerName.trim() || null,
        ownerEmail: form.ownerEmail.trim() || null,
        ownerPhone: form.ownerPhone.trim() || null,
        ownerAddress: form.ownerAddress.trim() || null,
        ownerIban: form.ownerIban.trim() || null,
        ownerUstId: form.ownerUstId.trim() || null,
        notes: form.notes.trim() || null,
      });
      setSavedAt(new Date());
    } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Einstellungen</h1>
          <div className="page-subtitle">Plattformname, Eigentümerdaten und Stammangaben</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary" onClick={save} disabled={busy}>
            {busy ? 'Speichert…' : 'Speichern'}
          </button>
        </div>
      </div>

      <form onSubmit={save} onKeyDown={(e) => { if (e.key === 'Enter' && e.target.tagName === 'INPUT') e.preventDefault(); }}>
        <div className="section">
          <div className="section-header"><h2 className="section-title">Plattform</h2></div>
          <div className="form-card">
            <div className="form-row">
              <label className="form-label">Name der Plattform</label>
              <div className="form-control">
                <input
                  className="form-input"
                  value={form.platformName}
                  onChange={e => update('platformName', e.target.value)}
                  placeholder="Hausgut"
                />
                <div className="form-hint">Erscheint in der Sidebar oben links und im Browser-Titel.</div>
              </div>
            </div>
          </div>
        </div>

        <div className="section">
          <div className="section-header"><h2 className="section-title">Eigentümer</h2></div>
          <div className="form-card">
            <div className="form-row">
              <label className="form-label">Name *</label>
              <div className="form-control">
                <input
                  className="form-input"
                  value={form.ownerName}
                  onChange={e => update('ownerName', e.target.value)}
                  placeholder="Vor- und Nachname"
                  autoFocus
                />
                <div className="form-hint">Erscheint in der Sidebar unten + auf erzeugten PDF-Verträgen als Vermieter.</div>
              </div>
            </div>
            <div className="form-row">
              <label className="form-label">E-Mail</label>
              <div className="form-control">
                <input
                  type="email" className="form-input"
                  value={form.ownerEmail}
                  onChange={e => update('ownerEmail', e.target.value)}
                  placeholder="vermieter@beispiel.de"
                />
              </div>
            </div>
            <div className="form-row">
              <label className="form-label">Telefon</label>
              <div className="form-control">
                <input
                  type="tel" className="form-input"
                  value={form.ownerPhone}
                  onChange={e => update('ownerPhone', e.target.value)}
                />
              </div>
            </div>
            <div className="form-row">
              <label className="form-label">Adresse</label>
              <div className="form-control">
                <textarea
                  className="form-input" rows={2}
                  value={form.ownerAddress}
                  onChange={e => update('ownerAddress', e.target.value)}
                  placeholder="Straße, PLZ, Ort"
                />
                <div className="form-hint">Erscheint im Briefkopf von Verträgen und Mahnungen.</div>
              </div>
            </div>
          </div>
        </div>

        <div className="section">
          <div className="section-header"><h2 className="section-title">Steuer & Bank</h2></div>
          <div className="form-card">
            <div className="form-row">
              <label className="form-label">USt-IdNr.</label>
              <div className="form-control">
                <input
                  className="form-input"
                  value={form.ownerUstId}
                  onChange={e => update('ownerUstId', e.target.value)}
                  placeholder="DE123456789"
                />
                <div className="form-hint">Optional, nur bei umsatzsteuerpflichtiger Vermietung (z.B. Gewerbeobjekte).</div>
              </div>
            </div>
            <div className="form-row">
              <label className="form-label">IBAN für Mietzahlungen</label>
              <div className="form-control">
                <input
                  className="form-input"
                  value={form.ownerIban}
                  onChange={e => update('ownerIban', e.target.value)}
                  placeholder="DE89 3704 0044 0532 0130 00"
                />
                <div className="form-hint">Erscheint in Verträgen und Mahnungen als Zahlungskonto.</div>
              </div>
            </div>
          </div>
        </div>

        <div className="section">
          <div className="section-header"><h2 className="section-title">Notiz</h2></div>
          <div className="form-card">
            <div className="form-row">
              <label className="form-label">Interne Notiz</label>
              <div className="form-control">
                <textarea
                  className="form-input" rows={3}
                  value={form.notes}
                  onChange={e => update('notes', e.target.value)}
                  placeholder="Notiz nur für dich, taucht nirgends in der App oder in PDFs auf."
                />
              </div>
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 24 }}>
          <button type="submit" className="btn btn-primary" disabled={busy}>
            {busy ? 'Speichert…' : 'Speichern'}
          </button>
          {savedAt && (
            <span style={{ color: 'var(--pos)', fontSize: 12.5 }}>
              ✓ gespeichert · {savedAt.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}
            </span>
          )}
          {err && <span style={{ color: 'var(--neg)', fontSize: 12.5 }}>⚠ {err}</span>}
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { SettingsPage });
