// screen-settings.jsx — settings with sub-pages: staff, flavours, AI training, corrections, notifications

function SettingsScreen({ currentUser, staff, setStaff, flavours, setFlavours, corrections, modelMeta, setModelMeta, addToast, notifyConfig, setNotifyConfig, pricingConfig, setPricingConfig, shopConfig, setShopConfig, baklavaPricing, setBaklavaPricing, fridgeConfig = { multiFridge: false, fridges: [] }, setFridgeConfig, onOrdersCleared, onCorrectionsCleared, notifications = [], onMarkAllNotifRead, onOpenOrder, initialSub }) {
  const isOwner = currentUser.role === 'owner';
  const [sub, setSub] = React.useState(initialSub || (isOwner ? 'staff' : 'notifications'));

  const items = [
    { key: 'staff', label: 'Llogaritë e stafit', icon: IconUsers, desc: 'Kush mund të kyçet' },
    { key: 'flavours', label: 'Shije tortash', icon: IconCake, desc: `${flavours.length} shije` },
    { key: 'pricing', label: 'Çmimet & madhësia', icon: IconEuro, desc: `${pricingConfig.diameters.length} madhësi · ${pricingConfig.personSizes.length} nivele personash` },
    { key: 'baklava', label: 'Çmimet e bakllava', icon: IconCake, desc: `Tepsi €${baklavaPricing.tepsi} · Kg €${baklavaPricing.kg}` },
    { key: 'fridges', label: 'Frigorifere', icon: IconCake, desc: fridgeConfig.multiFridge ? `${fridgeConfig.fridges.length} frigorifer të konfiguruara` : 'Numërim 1–8 (standard)' },
    ...(window.FEATURES.aiPricing ? [
      { key: 'ai', label: 'Modeli AI i çmimit', icon: IconBrain, desc: `Stërvitur së fundmi ${modelMeta.lastTrained}` },
      { key: 'corrections', label: 'Historia e korrigjimeve', icon: IconRefresh, desc: `${corrections.length} hyrje` },
    ] : []),
    { key: 'notifications', label: 'Njoftime', icon: IconBell, desc: 'WhatsApp + brenda aplikacionit' },
    { key: 'notif_history', label: 'Historiku i njoftimeve', icon: IconBell, desc: `${notifications.length} njoftime` },
    { key: 'backup', label: 'Backup & eksporti', icon: IconDownload, desc: 'Eksporto të dhëna + imazhe' },
    { key: 'danger', label: 'Zona e rrezikshme', icon: IconTrash, desc: 'Veprime të pakthyeshme' },
  ];

  if (!isOwner) {
    const staffItems = [
      { key: 'notifications', label: 'Njoftime', icon: IconBell, desc: 'Preferencat e njoftimeve' },
      { key: 'notif_history', label: 'Historiku i njoftimeve', icon: IconBell, desc: `${notifications.length} njoftime` },
    ];
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(220px, 1fr) minmax(0, 2.4fr)', gap: 24 }} className="settings-grid">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {staffItems.map(it => (
            <button key={it.key} onClick={() => setSub(it.key)} style={{
              display: 'flex', alignItems: 'center', gap: 14, padding: 14,
              background: sub === it.key ? 'var(--cream-2)' : 'transparent',
              border: '1px solid', borderColor: sub === it.key ? 'var(--line-2)' : 'transparent',
              borderRadius: 12, cursor: 'pointer', textAlign: 'left', color: 'var(--ink)',
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: sub === it.key ? 'var(--ink)' : 'var(--cream-2)', color: sub === it.key ? 'var(--cream)' : 'var(--ink)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <it.icon size={18} color={sub === it.key ? 'var(--cream)' : 'var(--ink)'} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{it.label}</div>
                <div className="muted" style={{ fontSize: 12 }}>{it.desc}</div>
              </div>
              <IconChevronRight size={14} color="var(--ink-mute)" />
            </button>
          ))}
          <div className="card" style={{ marginTop: 8, display: 'flex', gap: 12, alignItems: 'center', opacity: 0.55, padding: '12px 14px' }}>
            <IconLock size={14} />
            <p className="muted" style={{ margin: 0, fontSize: 12 }}>Cilësimet e tjera — vetëm pronari. Pyesni Ridvanin.</p>
          </div>
        </div>
        <div className="fade-in">
          {sub === 'notifications' && <NotificationSettings config={notifyConfig} setConfig={setNotifyConfig} addToast={addToast} />}
          {sub === 'notif_history' && <NotifHistory notifications={notifications} onMarkAllRead={onMarkAllNotifRead} onOpenOrder={onOpenOrder} />}
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(260px, 1fr) minmax(0, 2.4fr)', gap: 24 }} className="settings-grid">
      {/* Sub-nav */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {items.map(it => (
          <button key={it.key} onClick={() => setSub(it.key)} style={{
            display: 'flex', alignItems: 'center', gap: 14, padding: 14,
            background: sub === it.key ? 'var(--cream-2)' : 'transparent',
            border: '1px solid', borderColor: sub === it.key ? 'var(--line-2)' : 'transparent',
            borderRadius: 12, cursor: 'pointer', textAlign: 'left',
            color: 'var(--ink)',
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: sub === it.key ? 'var(--ink)' : 'var(--cream-2)',
              color: sub === it.key ? 'var(--cream)' : 'var(--ink)',
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              <it.icon size={18} color={sub === it.key ? 'var(--cream)' : 'var(--ink)'} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{it.label}</div>
              <div className="muted" style={{ fontSize: 12 }}>{it.desc}</div>
            </div>
            <IconChevronRight size={14} color="var(--ink-mute)" />
          </button>
        ))}
      </div>

      {/* Sub-page */}
      <div className="fade-in">
        {sub === 'staff' && <StaffSettings staff={staff} setStaff={setStaff} addToast={addToast} />}
        {sub === 'flavours' && <FlavoursSettings flavours={flavours} setFlavours={setFlavours} addToast={addToast} />}
        {sub === 'pricing' && <PricingSettings pricingConfig={pricingConfig} setPricingConfig={setPricingConfig} shopConfig={shopConfig} setShopConfig={setShopConfig} addToast={addToast} />}
        {sub === 'baklava' && <BaklavaSettings baklavaPricing={baklavaPricing} setBaklavaPricing={setBaklavaPricing} addToast={addToast} />}
        {sub === 'fridges' && <FridgeSettings fridgeConfig={fridgeConfig} setFridgeConfig={setFridgeConfig} addToast={addToast} />}
        {sub === 'ai' && <AISettings modelMeta={modelMeta} setModelMeta={setModelMeta} corrections={corrections} addToast={addToast} />}
        {sub === 'corrections' && <CorrectionsHistory corrections={corrections} />}
        {sub === 'notifications' && <NotificationSettings config={notifyConfig} setConfig={setNotifyConfig} addToast={addToast} />}
        {sub === 'notif_history' && <NotifHistory notifications={notifications} onMarkAllRead={onMarkAllNotifRead} onOpenOrder={onOpenOrder} />}
        {sub === 'backup' && <BackupSettings addToast={addToast} />}
        {sub === 'danger' && <DangerSettings addToast={addToast} onOrdersCleared={onOrdersCleared} onCorrectionsCleared={onCorrectionsCleared} setBaklavaPricing={setBaklavaPricing} setPricingConfig={setPricingConfig} />}
      </div>
    </div>
  );
}

// ── Staff ───────────────────────────────────────────────────────────────

function StaffSettings({ staff, setStaff, addToast }) {
  const [adding, setAdding] = React.useState(false);
  const [newUser, setNewUser] = React.useState({ username: '', name: '', role: 'staff', pin: '' });
  const [confirmRemove, setConfirmRemove] = React.useState(null);
  const [editing, setEditing] = React.useState(null); // staff id being edited
  const [editForm, setEditForm] = React.useState({ name: '', username: '', pin: '' });

  const startEdit = (s) => {
    setEditing(s.id);
    setEditForm({ name: s.name, username: s.username, pin: '' });
  };

  const submitEdit = () => {
    if (!editForm.name.trim() || !editForm.username.trim()) return;
    window.api.updateStaff(editing, {
      name: editForm.name,
      username: editForm.username,
      ...(editForm.pin ? { pin: editForm.pin } : {}),
    }).then(updated => {
      setStaff(staff.map(s => s.id === editing ? updated : s));
      setEditing(null);
      addToast('Llogaria u përditësua');
    }).catch(err => addToast(err.message || 'Dështoi përditësimi'));
  };

  const submit = () => {
    if (!newUser.username || !newUser.name || newUser.pin.length !== 4) return;
    window.api.createStaff({ username: newUser.username, name: newUser.name, role: newUser.role, pin: newUser.pin })
      .then(created => {
        setStaff([...staff, created]);
        setAdding(false);
        setNewUser({ username: '', name: '', role: 'staff', pin: '' });
        addToast('Llogaria e stafit u krijua');
      })
      .catch(err => addToast(err.message || 'Dështoi krijimi i llogarisë'));
  };

  return (
    <div>
      <SectionHeader
        title="Llogaritë e stafit"
        subtitle="Çdokush këtu mund të kyçet. Pronarët kanë akses të plotë, stafi ka të drejta të kufizuara."
        action={!adding && (
          <button className="btn" onClick={() => setAdding(true)}>
            <IconPlus size={16} color="var(--cream)" /> Shto staf
          </button>
        )}
      />

      {adding && (
        <div className="card" style={{ marginBottom: 16, background: 'var(--cream-2)' }}>
          <h3 className="display" style={{ margin: 0, fontSize: 18, fontWeight: 600, marginBottom: 14 }}>Llogari e re</h3>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 14 }}>
            <div className="field">
              <label className="field-label">Emri i plotë</label>
              <input className="input" placeholder="p.sh. Lulzim Krasniqi" value={newUser.name} onChange={e => setNewUser({...newUser, name: e.target.value})} />
            </div>
            <div className="field">
              <label className="field-label">Emri i përdoruesit</label>
              <input className="input" placeholder="p.sh. lulzim" value={newUser.username} onChange={e => setNewUser({...newUser, username: e.target.value.toLowerCase().replace(/\s/g, '')})} />
            </div>
            <div className="field">
              <label className="field-label">PIN 4-shifror</label>
              <input className="input tabular" type="text" inputMode="numeric" maxLength={4} placeholder="••••"
                     value={newUser.pin} onChange={e => setNewUser({...newUser, pin: e.target.value.replace(/\D/g, '').slice(0, 4)})} />
            </div>
            <div className="field">
              <label className="field-label">Roli</label>
              <div style={{ display: 'flex', gap: 6 }}>
                <button className={`chip ${newUser.role === 'staff' ? 'active' : ''}`} onClick={() => setNewUser({...newUser, role: 'staff'})}>Staf</button>
                <button className={`chip ${newUser.role === 'owner' ? 'active' : ''}`} onClick={() => setNewUser({...newUser, role: 'owner'})}>Pronar</button>
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button className="btn secondary" onClick={() => setAdding(false)}>Anulo</button>
            <button className="btn" disabled={!newUser.username || !newUser.name || newUser.pin.length !== 4} onClick={submit}>Krijo llogari</button>
          </div>
        </div>
      )}

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        {staff.map((s, i) => (
          <div key={s.id} style={{ borderTop: i ? '1px solid var(--line)' : 'none' }}>
            {editing === s.id ? (
              <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12, background: 'var(--cream-2)' }}>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 10 }}>
                  <div className="field">
                    <label className="field-label">Emri i plotë</label>
                    <input className="input" value={editForm.name} onChange={e => setEditForm({ ...editForm, name: e.target.value })} />
                  </div>
                  <div className="field">
                    <label className="field-label">Emri i përdoruesit</label>
                    <input className="input" value={editForm.username} onChange={e => setEditForm({ ...editForm, username: e.target.value.toLowerCase().replace(/\s/g, '') })} />
                  </div>
                  <div className="field">
                    <label className="field-label">PIN i ri (lini bosh për të njëjtin)</label>
                    <input className="input tabular" type="text" inputMode="numeric" maxLength={4} placeholder="••••"
                      value={editForm.pin} onChange={e => setEditForm({ ...editForm, pin: e.target.value.replace(/\D/g, '').slice(0, 4) })} />
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                  <button className="btn secondary sm" onClick={() => setEditing(null)}>Anulo</button>
                  <button className="btn sm"
                    disabled={!editForm.name.trim() || !editForm.username.trim() || (editForm.pin && editForm.pin.length !== 4)}
                    onClick={submitEdit}>
                    <IconCheck size={13} color="var(--cream)" /> Ruaj
                  </button>
                </div>
              </div>
            ) : (
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 16 }}>
                <Avatar name={s.name} color={s.color} size="lg" />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontWeight: 600 }}>{s.name}</span>
                    <span style={{
                      fontSize: 10.5, fontWeight: 700, padding: '2px 8px', borderRadius: 999,
                      background: s.role === 'owner' ? 'var(--ink)' : 'var(--cream-2)',
                      color: s.role === 'owner' ? 'var(--cream)' : 'var(--ink-2)',
                      textTransform: 'uppercase', letterSpacing: '0.08em',
                    }}>{s.role}</span>
                  </div>
                  <div className="muted" style={{ fontSize: 13 }}>@{s.username} · kyçje e fundit {s.last_login}</div>
                </div>
                <button className="btn secondary sm" onClick={() => startEdit(s)}>
                  <IconEdit size={13} /> Ndrysho
                </button>
                {s.role !== 'owner' && (
                  <button className="btn danger sm" onClick={() => setConfirmRemove(s)}>
                    Hiq
                  </button>
                )}
              </div>
            )}
          </div>
        ))}
      </div>

      <ConfirmDialog
        open={!!confirmRemove}
        title={`Hiq ${confirmRemove?.name}?`}
        body={`@${confirmRemove?.username} nuk do të mund të kyçet më. Historia e porosive mbetet.`}
        confirmLabel="Po, hiq"
        danger
        onConfirm={() => {
          window.api.deleteStaff(confirmRemove.id)
            .then(() => { setStaff(staff.filter(s => s.id !== confirmRemove.id)); addToast('Stafi u hoq'); })
            .catch(err => addToast(err.message || 'Dështoi heqja e stafit'));
          setConfirmRemove(null);
        }}
        onCancel={() => setConfirmRemove(null)}
      />
    </div>
  );
}

// ── Flavours ────────────────────────────────────────────────────────────

function FlavoursSettings({ flavours, setFlavours, addToast }) {
  const [newFlavour, setNewFlavour] = React.useState('');
  const addFlavour = () => {
    const name = newFlavour.trim();
    if (!name || flavours.includes(name)) return;
    window.api.addFlavour(name)
      .then(() => { setFlavours([...flavours, name]); setNewFlavour(''); addToast('Shija u shtua'); })
      .catch(err => addToast(err.message || 'Dështoi shtimi i shijës'));
  };
  const removeFlavour = (f) => {
    window.api.removeFlavour(f)
      .then(() => { setFlavours(flavours.filter(x => x !== f)); addToast(`${f} u hoq`); })
      .catch(err => addToast(err.message || 'Dështoi heqja e shijës'));
  };
  return (
    <div>
      <SectionHeader
        title="Shije tortash"
        subtitle="Shijet që shfaqen në formularin e porosisë standarde."
      />

      <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
        <input className="input" placeholder="Shto një shije të re…"
          value={newFlavour}
          onChange={e => setNewFlavour(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && addFlavour()}
        />
        <button className="btn" disabled={!newFlavour.trim()} onClick={addFlavour}>
          <IconPlus size={16} color="var(--cream)" /> Shto
        </button>
      </div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {flavours.map(f => (
          <div key={f} style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '8px 6px 8px 16px',
            background: 'white',
            border: '1px solid var(--line)',
            borderRadius: 999,
            fontSize: 14,
            fontWeight: 500,
          }}>
            <IconCake size={14} />
            {f}
            <button onClick={() => removeFlavour(f)} className="icon-btn" style={{ width: 24, height: 24 }}>
              <IconX size={12} />
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── AI Settings (Training!) ─────────────────────────────────────────────

function AISettings({ modelMeta, setModelMeta, corrections, addToast }) {
  const pendingCount = corrections.filter(c => !c.used).length;
  const [training, setTraining] = React.useState(null); // null or { epoch, loss, progress }
  const [showCold, setShowCold] = React.useState(modelMeta.lastTrained === 'never');

  const startTraining = (isCold) => {
    setTraining({ epoch: 0, loss: 22.5, progress: 0, isCold });
    const totalEpochs = 20;
    const start = Date.now();
    const dur = 7000;
    const tick = () => {
      const elapsed = Date.now() - start;
      const t = Math.min(1, elapsed / dur);
      const epoch = Math.min(totalEpochs, Math.floor(t * totalEpochs));
      const loss = 22.5 * Math.pow(0.78, t * 8) + 1.2 + Math.random() * 0.3;
      setTraining({ epoch, loss, progress: t, isCold, history: getLossHistory(t) });
      if (t < 1) {
        requestAnimationFrame(tick);
      } else {
        setTimeout(() => {
          setTraining(null);
          setModelMeta({
            ...modelMeta,
            lastTrained: 'tani',
            corrections: isCold ? 0 : pendingCount,
            version: (modelMeta.version || 5) + 1,
            mae: (1.5 + Math.random() * 0.8).toFixed(2),
          });
          addToast(isCold ? 'Modeli fillestar u stërvit · gati për të parashikuar' : 'Modeli u ristërvit · përmirësimet janë gati');
          setShowCold(false);
        }, 600);
      }
    };
    requestAnimationFrame(tick);
  };

  return (
    <div>
      <SectionHeader
        title="Modeli AI i çmimit"
        subtitle="Regresion EfficientNetB0 — parashikon çmimin e fotove të tortave të personalizuara."
      />

      {/* Model status card */}
      <div className="card-warm" style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18, flexWrap: 'wrap' }}>
          <div style={{
            width: 64, height: 64, borderRadius: 18,
            background: 'var(--ink)', color: 'var(--cream)',
            display: 'grid', placeItems: 'center', flexShrink: 0,
            position: 'relative',
          }}>
            <IconBrain size={28} color="var(--cream)" />
            <span style={{
              position: 'absolute', bottom: -4, right: -4,
              background: 'var(--green)', width: 16, height: 16, borderRadius: '50%',
              border: '3px solid var(--cream)',
            }} />
          </div>
          <div style={{ flex: 1, minWidth: 240 }}>
            <div style={{ display: 'flex', gap: 10, alignItems: 'baseline' }}>
              <h3 className="display" style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>Model v{modelMeta.version}</h3>
              <span className="conf-pill high" style={{ background: 'var(--green-soft)', color: '#285d3f', fontSize: 11 }}>
                <span className="badge-dot" style={{ background: 'var(--green)' }} /> Aktiv
              </span>
            </div>
            <div className="muted" style={{ fontSize: 13, marginTop: 4, marginBottom: 14 }}>
              Stërvitur së fundmi {modelMeta.lastTrained} · MAE €{modelMeta.mae} · {modelMeta.imageCount} foto stërvitjeje
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: 16 }}>
              <Metric label="Set stërvitjeje" value={modelMeta.imageCount} sub="foto tortash" />
              <Metric label="Korrigjime" value={corrections.length} sub={`${pendingCount} në pritje`} />
              <Metric label="MAE" value={`€${modelMeta.mae}`} sub="gabim mesatar absolut" />
              <Metric label="Ristërvitje auto" value="02:00" sub="çdo natë" />
            </div>
          </div>
        </div>
      </div>

      {/* Training progress / triggers */}
      {training ? (
        <TrainingProgress training={training} />
      ) : showCold ? (
        <div className="card" style={{ background: 'linear-gradient(135deg, rgba(212,96,122,0.06), rgba(76,175,130,0.06))', border: '1px solid var(--rose-soft)' }}>
          <h3 className="display" style={{ margin: 0, fontSize: 22, fontWeight: 600, marginBottom: 8 }}>Stërvitni modelin tuaj të parë</h3>
          <p style={{ margin: 0, marginBottom: 14, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: 540 }}>
            Kemi mbledhur 52 foto tortash me çmime të konfirmuara nga porositë tuaja të kaluara. Kjo stërvit kokën e regresionit nga EfficientNetB0 i parastërvitur në ImageNet. Zgjat 2–5 minuta.
          </p>
          <button className="btn rose lg" onClick={() => startTraining(true)}>
            <IconSparkle size={18} color="white" /> Stërvit modelin fillestar
          </button>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
          <div className="card">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <IconRefresh size={18} />
              <strong>Ristërvit tani</strong>
            </div>
            <p className="muted" style={{ margin: 0, marginBottom: 14, fontSize: 13.5 }}>
              {pendingCount > 0
                ? `${pendingCount} ${pendingCount === 1 ? 'korrigjim i ri është' : 'korrigjime të reja janë'} grumbulluar që nga stërvitja e fundit.`
                : 'Asnjë korrigjim i ri që nga stërvitja e fundit.'}
            </p>
            <button className="btn" onClick={() => startTraining(false)} disabled={pendingCount === 0}>
              Ristërvit modelin
            </button>
          </div>
          <div className="card">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <IconClock size={18} />
              <strong>Ristërvitje automatike</strong>
            </div>
            <p className="muted" style={{ margin: 0, marginBottom: 14, fontSize: 13.5 }}>
              Çdo natë në orën 02:00, sistemi ristërvit nëse kanë mbërritur korrigjime të reja. Nuk duhet të prekni asgjë.
            </p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5 }}>
              <span className="badge-dot" style={{ background: 'var(--green)' }} /> Aktivizuar
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function Metric({ label, value, sub }) {
  return (
    <div>
      <div className="display tabular" style={{ fontSize: 22, fontWeight: 600 }}>{value}</div>
      <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>{label}</div>
      <div className="muted" style={{ fontSize: 11 }}>{sub}</div>
    </div>
  );
}

function getLossHistory(t) {
  const points = 30;
  const result = [];
  for (let i = 0; i < points; i++) {
    const tt = (i / points) * t;
    result.push(22.5 * Math.pow(0.78, tt * 8) + 1.2 + Math.sin(i * 0.7) * 0.5);
  }
  return result;
}

function TrainingProgress({ training }) {
  const pct = Math.round(training.progress * 100);
  const history = training.history || [22.5];
  const maxL = Math.max(...history);
  const minL = Math.min(...history);
  const path = history.map((v, i) => {
    const x = (i / (history.length - 1 || 1)) * 100;
    const y = 100 - ((v - minL) / (maxL - minL || 1)) * 100;
    return `${i === 0 ? 'M' : 'L'} ${x.toFixed(2)} ${y.toFixed(2)}`;
  }).join(' ');

  return (
    <div className="card-warm" style={{ border: '1px solid var(--rose-soft)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
        <span className="spinner lg" style={{ borderColor: 'rgba(212,96,122,0.2)', borderTopColor: 'var(--rose)' }} />
        <div>
          <h3 className="display" style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>
            {training.isCold ? 'Duke stërvitur modelin fillestar…' : 'Duke ristërvit modelin…'}
          </h3>
          <div className="muted" style={{ fontSize: 13 }}>Mos e mbyllni këtë skedë. Zgjat 2–5 minuta.</div>
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
        <span style={{ fontWeight: 600 }}>Epoch <span className="tabular display">{training.epoch}</span>/20</span>
        <span className="muted tabular">{pct}%</span>
      </div>
      <div className="confidence-track" style={{ height: 8, marginBottom: 18 }}>
        <div className="confidence-fill" style={{ width: `${pct}%`, background: 'var(--rose)' }} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div>
          <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Humbja aktuale</div>
          <div className="display tabular" style={{ fontSize: 28, fontWeight: 600 }}>{training.loss.toFixed(2)}</div>
          <div className="muted" style={{ fontSize: 12 }}>MSE · Adam optimizer · LR 1e-3</div>
        </div>
        <div>
          <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Trendi i humbjes</div>
          <svg viewBox="0 0 100 30" preserveAspectRatio="none" style={{ width: '100%', height: 50 }}>
            <path d={path} stroke="var(--rose)" strokeWidth="1.5" fill="none" vectorEffect="non-scaling-stroke" />
          </svg>
        </div>
      </div>

      <div style={{ marginTop: 18, padding: 12, background: 'white', borderRadius: 10, fontSize: 12.5, color: 'var(--ink-2)', fontFamily: 'JetBrains Mono, ui-monospace, monospace' }}>
        <div className="muted" style={{ marginBottom: 4 }}>// training.log</div>
        <div>{training.isCold ? 'fine-tuning EfficientNetB0 (regression head)' : 'loading checkpoint v' + (training.epoch || 5)}</div>
        <div>batch_size=16 · epochs=20 · device=cuda:0</div>
        <div style={{ color: 'var(--green)' }}>epoch {String(training.epoch).padStart(2, '0')} · loss={training.loss.toFixed(4)} · lr=1.0e-3</div>
      </div>
    </div>
  );
}

// ── Corrections history ────────────────────────────────────────────────

function CorrectionsHistory({ corrections }) {
  return (
    <div>
      <SectionHeader
        title="Historia e korrigjimeve"
        subtitle="Çdo herë që keni rregulluar një parashikim AI — këto stërvit modelin."
      />

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: '60px 1fr 100px 100px 80px 80px',
          padding: '12px 18px',
          fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em',
          color: 'var(--ink-mute)',
          borderBottom: '1px solid var(--line)',
          gap: 12,
        }} className="corr-header">
          <span></span>
          <span>Porosia</span>
          <span style={{ textAlign: 'right' }}>Parashikuar</span>
          <span style={{ textAlign: 'right' }}>Korrekte</span>
          <span style={{ textAlign: 'right' }}>Δ</span>
          <span style={{ textAlign: 'right' }}>Statusi</span>
        </div>
        {corrections.map(c => {
          const diff = c.correct - c.predicted;
          return (
            <div key={c.id} style={{
              display: 'grid',
              gridTemplateColumns: '60px 1fr 100px 100px 80px 80px',
              padding: '14px 18px',
              alignItems: 'center', gap: 12,
              borderBottom: '1px solid var(--line)',
            }} className="corr-row">
              <div style={{ width: 44, height: 44, borderRadius: 10, overflow: 'hidden' }}>
                <CakeArt name={c.art} style={{ width: '100%', height: '100%' }} />
              </div>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{c.customer}</div>
                <div className="muted" style={{ fontSize: 12 }}>#{c.order.slice(-4)} · {window.relativeDay(c.at)}</div>
              </div>
              <div className="tabular" style={{ textAlign: 'right', color: 'var(--ink-mute)' }}>{window.formatEURP(c.predicted)}</div>
              <div className="tabular display" style={{ textAlign: 'right', fontWeight: 600, fontSize: 15 }}>{window.formatEURP(c.correct)}</div>
              <div className="tabular" style={{
                textAlign: 'right',
                fontWeight: 600,
                color: diff > 0 ? 'var(--green)' : 'var(--red)',
                fontSize: 13,
              }}>
                {diff > 0 ? '+' : ''}{window.formatEURP(diff)}
              </div>
              <div style={{ textAlign: 'right' }}>
                {c.used ? (
                  <span className="conf-pill" style={{ background: 'var(--green-soft)', color: '#285d3f', fontSize: 10 }}>
                    Stërvitur
                  </span>
                ) : (
                  <span className="conf-pill" style={{ background: 'var(--amber-soft)', color: '#7a5418', fontSize: 10 }}>
                    Në pritje
                  </span>
                )}
              </div>
            </div>
          );
        })}
      </div>

      <p className="muted" style={{ marginTop: 16, fontSize: 13, textAlign: 'center' }}>
        Korrigjimet në pritje aplikohen gjatë stërvitjes së radhës (sonte në 02:00).
      </p>
    </div>
  );
}

// ── Notification history ────────────────────────────────────────────────

function NotifHistory({ notifications, onMarkAllRead, onOpenOrder }) {
  const unread = notifications.filter(n => !n.is_read).length;
  return (
    <div>
      <SectionHeader
        title="Historiku i njoftimeve"
        subtitle="Të gjitha njoftimet, lexuara dhe të palexuara."
        action={unread > 0 && (
          <button className="btn secondary" style={{ height: 34, fontSize: 13 }} onClick={onMarkAllRead}>
            Shëno të gjitha si të lexuara
          </button>
        )}
      />
      {notifications.length === 0 ? (
        <div className="card" style={{ textAlign: 'center', padding: 32 }}>
          <p className="muted" style={{ margin: 0 }}>Asnjë njoftim akoma.</p>
        </div>
      ) : (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          {notifications.map((n, i) => (
            <div key={n.id} onClick={() => n.order_id && onOpenOrder(n.order_id)} style={{
              padding: '14px 18px',
              cursor: n.order_id ? 'pointer' : 'default',
              borderBottom: i < notifications.length - 1 ? '1px solid var(--line)' : 'none',
              background: !n.is_read ? 'var(--cream-2)' : 'transparent',
              display: 'flex', gap: 12, alignItems: 'flex-start',
            }}>
              <div style={{ width: 34, height: 34, borderRadius: 8, flexShrink: 0, display: 'grid', placeItems: 'center', background: window.kindBg(n.kind) }}>
                {window.kindIcon(n.kind)}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: !n.is_read ? 600 : 400, lineHeight: 1.35 }}>{n.message}</div>
                <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>{n.created_at}</div>
              </div>
              {!n.is_read && <div style={{ width: 8, height: 8, background: 'var(--rose)', borderRadius: '50%', flexShrink: 0, marginTop: 6 }} />}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Notifications ──────────────────────────────────────────────────────

function WhatsAppFeatureFlag({ config, setConfig, addToast }) {
  const [testBusy, setTestBusy] = React.useState(false);
  const save = (patch) => {
    const next = { ...config, ...patch };
    setConfig(next);
    if ('waEnabled' in patch) window.api.updateSetting('whatsapp_notifications_enabled', patch.waEnabled ? '1' : '0');
    if ('waCallmebotKey' in patch) window.api.updateSetting('whatsapp_callmebot_key', patch.waCallmebotKey);
    if ('phone' in patch) window.api.updateSetting('notify_phone', patch.phone);
  };
  const test = () => {
    setTestBusy(true);
    window.api.testWhatsApp(config.phone, config.waCallmebotKey)
      .then(r => addToast(r.ok ? 'Mesazh testues u dërgua ✓' : 'Dërgimi dështoi (kodo ' + r.status + ')'))
      .catch(() => addToast('Gabim gjatë dërgimit'))
      .finally(() => setTestBusy(false));
  };

  return (
    <div className="card" style={{ border: '1px solid rgba(37,211,102,0.3)', background: 'rgba(37,211,102,0.04)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, marginBottom: config.waEnabled ? 16 : 0 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, background: '#25d36622', color: '#1f9d52', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <IconWhatsApp size={20} color="#1f9d52" />
          </div>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontWeight: 600 }}>WhatsApp Live</span>
              <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.06em', padding: '2px 7px', borderRadius: 20, background: '#25d36622', color: '#1a8a44' }}>BETA</span>
            </div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 1 }}>Njofto menjëherë për porosi të reja &amp; gati</div>
          </div>
        </div>
        <Toggle on={config.waEnabled} onChange={(v) => save({ waEnabled: v })} />
      </div>

      {config.waEnabled && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, paddingTop: 16, borderTop: '1px solid rgba(37,211,102,0.2)' }}>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-mute)', display: 'block', marginBottom: 5 }}>NUMRI WHATSAPP</label>
            <input className="input" placeholder="+355 69 …" value={config.phone}
              onChange={e => save({ phone: e.target.value })} />
          </div>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-mute)', display: 'block', marginBottom: 5 }}>CALLMEBOT API KEY</label>
            <input className="input" placeholder="123456" value={config.waCallmebotKey}
              onChange={e => save({ waCallmebotKey: e.target.value })} />
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-mute)', lineHeight: 1.55, background: 'var(--cream-2)', borderRadius: 8, padding: '10px 12px' }}>
            Si ta konfigurosh: Dërgo mesazhin <strong>"I allow callmebot to send me messages"</strong> te <strong>+34 644 59 87 13</strong> në WhatsApp. Do të marrësh API key-n automatikisht.
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn secondary" onClick={test} disabled={testBusy || !config.phone || !config.waCallmebotKey}>
              <IconWhatsApp size={14} color="#1f9d52" /> {testBusy ? 'Duke dërguar…' : 'Dërgo test'}
            </button>
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-mute)' }}>
            <strong>Njofton kur:</strong> porosi e re krijohet · porosi shënohet "Gati" · kujtues ditor
          </div>
        </div>
      )}
    </div>
  );
}

function NotificationSettings({ config, setConfig, addToast }) {
  return (
    <div>
      <SectionHeader
        title="Njoftime"
        subtitle="Kujtuese ditore WhatsApp për tortat e afruara."
      />

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="card">
          <h3 className="display" style={{ margin: 0, fontSize: 18, fontWeight: 600, marginBottom: 14 }}>Kanalet</h3>

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0' }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--cream-2)', display: 'grid', placeItems: 'center' }}>
                <IconBell size={18} />
              </div>
              <div>
                <div style={{ fontWeight: 600 }}>Njoftime brenda aplikacionit</div>
                <div className="muted" style={{ fontSize: 12.5 }}>Ikona e ziles · sipër çdo ekrani</div>
              </div>
            </div>
            <Toggle on={config.inApp} onChange={(v) => setConfig({ ...config, inApp: v })} />
          </div>
        </div>

        <WhatsAppFeatureFlag config={config} setConfig={setConfig} addToast={addToast} />

        <PushNotificationSettings addToast={addToast} />
      </div>
    </div>
  );
}

// ── Push notification preferences ──────────────────────────────────────

function PushNotificationSettings({ addToast }) {
  const [supported] = React.useState(() => 'Notification' in window && 'serviceWorker' in navigator && 'PushManager' in window);
  const [permission, setPermission] = React.useState(() => supported ? Notification.permission : 'denied');
  const [subscribed, setSubscribed] = React.useState(false);
  const [prefs, setPrefs] = React.useState({ new_order: true, order_ready: true, daily_digest: true, due_tomorrow: true });
  const [loading, setLoading] = React.useState(false);
  const [digestTime, setDigestTime] = React.useState('06:00');
  const [reminderTime, setReminderTime] = React.useState('15:00');

  React.useEffect(() => {
    if (!supported) return;
    window.api.getPushPreferences().then(setPrefs).catch(() => {});
    navigator.serviceWorker.ready.then(reg => reg.pushManager.getSubscription()).then(sub => setSubscribed(!!sub)).catch(() => {});
    window.api.getSettings().then(s => {
      if (s.push_digest_time)   setDigestTime(s.push_digest_time);
      if (s.push_reminder_time) setReminderTime(s.push_reminder_time);
    }).catch(() => {});
  }, []);

  const enable = async () => {
    setLoading(true);
    try {
      const perm = await Notification.requestPermission();
      setPermission(perm);
      if (perm !== 'granted') { addToast('Leja u refuzua nga shfletuesi'); return; }
      const { publicKey } = await window.api.getPushVapidKey();
      if (!publicKey) { addToast('Push nuk është konfiguruar nga serveri'); return; }
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: publicKey,
      });
      await window.api.subscribePush(sub.toJSON());
      setSubscribed(true);
      addToast('Njoftimet push u aktivizuan');
    } catch (e) {
      addToast('Gabim gjatë aktivizimit: ' + e.message);
    } finally {
      setLoading(false);
    }
  };

  const disable = async () => {
    setLoading(true);
    try {
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.getSubscription();
      if (sub) {
        await window.api.unsubscribePush(sub.endpoint);
        await sub.unsubscribe();
      }
      setSubscribed(false);
      addToast('Njoftimet push u çaktivizuan');
    } catch (e) {
      addToast('Gabim: ' + e.message);
    } finally {
      setLoading(false);
    }
  };

  const savePrefs = (next) => {
    setPrefs(next);
    window.api.updatePushPreferences(next).catch(() => addToast('Gabim gjatë ruajtjes'));
  };

  const saveTime = (key, value) => {
    window.api.updateSetting(key, value).then(() => addToast('Ora u ruajt')).catch(() => addToast('Gabim gjatë ruajtjes'));
  };

  const EVENTS = [
    { key: 'new_order',    label: 'Porosi e re',       desc: 'Kur krijohet një porosi e re' },
    { key: 'order_ready',  label: 'Porosi gati',        desc: 'Kur statusi ndryshon në "gati"' },
    { key: 'daily_digest', label: 'Kujtues mëngjesit',  desc: 'Porositë që duhen dorëzuar sot' },
    { key: 'due_tomorrow', label: 'Kujtues mbrëmjes',   desc: 'Porositë që dorëzohen nesër' },
  ];

  return (
    <div className="card">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div>
          <h3 className="display" style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Njoftime Push</h3>
          <p className="muted" style={{ margin: '3px 0 0', fontSize: 13 }}>Njoftime direkte në pajisje, edhe kur aplikacioni është i mbyllur</p>
        </div>
        {supported ? (
          subscribed
            ? <button className="chip" onClick={disable} disabled={loading} style={{ height: 36, padding: '0 16px', color: '#8c2e2e' }}>
                {loading ? 'Duke çaktivizuar…' : 'Çaktivizo'}
              </button>
            : <button className="btn" onClick={enable} disabled={loading || permission === 'denied'}>
                {loading ? 'Duke aktivizuar…' : 'Aktivizo'}
              </button>
        ) : (
          <span className="muted" style={{ fontSize: 13 }}>Shfletuesi nuk suporton</span>
        )}
      </div>

      {permission === 'denied' && (
        <div style={{ marginBottom: 14, padding: '10px 14px', background: 'rgba(140,46,46,0.06)', borderRadius: 8, border: '1px solid rgba(140,46,46,0.15)', fontSize: 13, color: '#8c2e2e' }}>
          Njoftimet janë bllokuar nga shfletuesi. Hap cilësimet e shfletuesit dhe lejo njoftimet për këtë faqe.
        </div>
      )}

      <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14, display: 'flex', flexDirection: 'column', gap: 0 }}>
        <div className="muted" style={{ fontSize: 11.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 10 }}>Oraret e kujtueses (UTC)</div>

        {[
          { key: 'push_digest_time',   label: 'Kujtues mëngjesit', val: digestTime,   set: setDigestTime },
          { key: 'push_reminder_time', label: 'Kujtues mbrëmjes',  val: reminderTime, set: setReminderTime },
        ].map((row, i, arr) => (
          <div key={row.key} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: i < arr.length - 1 ? '1px solid var(--line)' : 'none' }}>
            <div style={{ fontWeight: 600, fontSize: 14 }}>{row.label}</div>
            <input className="input" type="time" value={row.val}
              style={{ width: 120 }}
              onChange={e => row.set(e.target.value)}
              onBlur={e => saveTime(row.key, e.target.value)} />
          </div>
        ))}

        <p className="muted" style={{ fontSize: 11.5, margin: '8px 0 0' }}>
          Orët janë në UTC. Shqipëria është UTC+1 (dimër) / UTC+2 (verë) — zbrit 1–2 orë nga ora lokale.
        </p>
      </div>

      {subscribed && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0, borderTop: '1px solid var(--line)', paddingTop: 14, marginTop: 14 }}>
          <div className="muted" style={{ fontSize: 11.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 10 }}>Cilëso ngjarjet</div>
          {EVENTS.map((ev, i) => (
            <div key={ev.key} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: i < EVENTS.length - 1 ? '1px solid var(--line)' : 'none' }}>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{ev.label}</div>
                <div className="muted" style={{ fontSize: 12 }}>{ev.desc}</div>
              </div>
              <Toggle on={!!prefs[ev.key]} onChange={v => savePrefs({ ...prefs, [ev.key]: v })} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Pricing & dimensions ────────────────────────────────────────────────

function PricingSettings({ pricingConfig, setPricingConfig, shopConfig, setShopConfig, addToast }) {
  const { diameters, personSizes, basePrices } = pricingConfig;
  const [newDiam, setNewDiam] = React.useState('');
  const [newSize, setNewSize] = React.useState('');
  const [newPrice, setNewPrice] = React.useState('');
  const [editingPrice, setEditingPrice] = React.useState({});

  const savePricing = (d, ps, bp) => {
    Promise.all([
      window.api.updateSetting('cake_diameters', JSON.stringify(d)),
      window.api.updateSetting('cake_person_sizes', JSON.stringify(ps)),
      window.api.updateSetting('cake_base_prices', JSON.stringify(bp)),
    ]).catch(() => addToast('Gabim gjatë ruajtjes'));
  };

  const addDiameter = () => {
    const n = parseInt(newDiam);
    if (!n || n <= 0 || diameters.includes(n)) return;
    const next = [...diameters, n].sort((a, b) => a - b);
    setPricingConfig({ ...pricingConfig, diameters: next });
    savePricing(next, personSizes, basePrices);
    setNewDiam('');
    addToast(`Diametri ${n}cm u shtua`);
  };

  const removeDiameter = (d) => {
    const next = diameters.filter(x => x !== d);
    setPricingConfig({ ...pricingConfig, diameters: next });
    savePricing(next, personSizes, basePrices);
    addToast(`${d}cm u hoq`);
  };

  const addPersonRow = () => {
    const s = parseInt(newSize);
    const p = parseFloat(newPrice);
    if (!s || s <= 0 || isNaN(p) || personSizes.includes(s)) return;
    const nextSizes = [...personSizes, s].sort((a, b) => a - b);
    const nextPrices = { ...basePrices, [s]: p };
    setPricingConfig({ ...pricingConfig, personSizes: nextSizes, basePrices: nextPrices });
    savePricing(diameters, nextSizes, nextPrices);
    setNewSize(''); setNewPrice('');
    addToast(`Niveli ${s}-person u shtua`);
  };

  const removePersonRow = (s) => {
    const nextSizes = personSizes.filter(x => x !== s);
    const nextPrices = { ...basePrices };
    delete nextPrices[s];
    setPricingConfig({ ...pricingConfig, personSizes: nextSizes, basePrices: nextPrices });
    savePricing(diameters, nextSizes, nextPrices);
    addToast(`Niveli ${s}-person u hoq`);
  };

  const commitPrice = (s, val) => {
    const n = parseFloat(val);
    if (!isNaN(n) && n >= 0) {
      const nextPrices = { ...basePrices, [s]: n };
      setPricingConfig({ ...pricingConfig, basePrices: nextPrices });
      savePricing(diameters, personSizes, nextPrices);
      addToast('Çmimi u përditësua');
    }
    setEditingPrice(ep => { const next = { ...ep }; delete next[s]; return next; });
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader
        title="Çmimet & madhësia"
        subtitle="Konfiguroni madhësinë dhe çmimet referencë të përdorura në formularin e porosisë."
      />

      {/* Staff order visibility */}
      <div className="card">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 20, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 200 }}>
            <h3 className="display" style={{ margin: '0 0 4px', fontSize: 18, fontWeight: 600 }}>Dukshmëria e porosive nga stafi</h3>
            <p className="muted" style={{ margin: 0, fontSize: 13, lineHeight: 1.5 }}>
              Stafi sheh porositë me afat brenda kaq ditëve. Pronarët shohin gjithmonë gjithçka.
            </p>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
            {[7, 14, 30, 60, 90].map(d => (
              <button key={d} onClick={() => { setShopConfig({ ...shopConfig, daysAhead: d }); addToast(`Dukshmëria e stafit u vendos në ${d} ditë`); }}
                className="chip"
                style={{
                  height: 36, padding: '0 14px', fontSize: 13, fontWeight: 600,
                  background: shopConfig.daysAhead === d ? 'var(--ink)' : 'transparent',
                  color: shopConfig.daysAhead === d ? 'var(--cream)' : 'var(--ink-2)',
                  borderColor: shopConfig.daysAhead === d ? 'var(--ink)' : 'var(--line)',
                }}>
                {d}d
              </button>
            ))}
            <div style={{ position: 'relative', width: 90 }}>
              <input className="input" type="number" min="1" max="365"
                value={shopConfig.daysAhead}
                onChange={e => {
                  const n = parseInt(e.target.value);
                  if (!isNaN(n) && n > 0) setShopConfig({ ...shopConfig, daysAhead: n });
                }}
                style={{ paddingRight: 28, textAlign: 'center' }}
              />
              <span style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', fontSize: 11, color: 'var(--ink-mute)', pointerEvents: 'none' }}>d</span>
            </div>
          </div>
        </div>
      </div>

      {/* Staff past-order visibility */}
      <div className="card">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 20 }}>
          <div style={{ flex: 1, minWidth: 200 }}>
            <h3 className="display" style={{ margin: '0 0 4px', fontSize: 18, fontWeight: 600 }}>Stafi sheh porositë e përfunduara</h3>
            <p className="muted" style={{ margin: 0, fontSize: 13, lineHeight: 1.5 }}>
              Kur është joaktiv, porositë e dorëzuara dhe të anuluara fshihen nga stafi. Pronarët gjithmonë shohin të gjitha.
            </p>
          </div>
          <Toggle
            on={shopConfig.staffSeePastOrders}
            onChange={v => { setShopConfig({ ...shopConfig, staffSeePastOrders: v }); addToast(v ? 'Stafi mund të shohë porositë e përfunduara' : 'Porositë e përfunduara fshihen nga stafi'); }}
          />
        </div>
      </div>

      {/* Round cake diameters */}
      <div className="card">
        <h3 className="display" style={{ margin: '0 0 6px', fontSize: 18, fontWeight: 600 }}>Diametrat e tortave të rrumbullakëta</h3>
        <p className="muted" style={{ margin: '0 0 14px', fontSize: 13 }}>Madhësia në cm e disponueshme gjatë vendosjes së një porosie torte të rrumbullakët.</p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 14 }}>
          {diameters.map(d => (
            <div key={d} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '7px 6px 7px 14px',
              background: 'white', border: '1px solid var(--line)', borderRadius: 999,
              fontSize: 14, fontWeight: 600,
            }}>
              <span className="tabular">{d}</span>
              <span style={{ fontWeight: 400, color: 'var(--ink-mute)', fontSize: 12, marginLeft: 1 }}>cm</span>
              <button onClick={() => removeDiameter(d)} className="icon-btn" style={{ width: 22, height: 22 }}>
                <IconX size={11} />
              </button>
            </div>
          ))}
          {diameters.length === 0 && (
            <span className="muted" style={{ fontSize: 13, fontStyle: 'italic' }}>Asnjë diametër i konfiguruar</span>
          )}
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ position: 'relative', width: 120 }}>
            <input className="input" type="number" min="1" placeholder="e.g. 16"
              value={newDiam} onChange={e => setNewDiam(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addDiameter()}
              style={{ paddingRight: 32 }}
            />
            <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 12, color: 'var(--ink-mute)', pointerEvents: 'none' }}>cm</span>
          </div>
          <button className="btn" disabled={!newDiam} onClick={addDiameter}>
            <IconPlus size={15} color="var(--cream)" /> Shto
          </button>
        </div>
      </div>

      {/* Persons / price table */}
      <div className="card">
        <h3 className="display" style={{ margin: '0 0 6px', fontSize: 18, fontWeight: 600 }}>Personat → tabela e çmimeve</h3>
        <p className="muted" style={{ margin: '0 0 14px', fontSize: 13 }}>Çmimet referencë që shfaqen gjatë krijimit të një porosie standarde. Klikoni mbi çmim për ta ndryshuar.</p>

        <div className="card" style={{ padding: 0, overflow: 'hidden', marginBottom: 16 }}>
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr 44px',
            padding: '10px 16px', gap: 12,
            fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em',
            color: 'var(--ink-mute)', borderBottom: '1px solid var(--line)',
          }}>
            <span>Persona</span>
            <span>Çmim reference</span>
            <span />
          </div>
          {personSizes.length === 0 && (
            <div className="muted" style={{ padding: '16px', textAlign: 'center', fontSize: 13, fontStyle: 'italic' }}>Asnjë nivel akoma</div>
          )}
          {personSizes.map((s, i) => (
            <div key={s} style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr 44px',
              padding: '10px 16px', gap: 12, alignItems: 'center',
              borderBottom: i < personSizes.length - 1 ? '1px solid var(--line)' : 'none',
            }}>
              <span style={{ fontWeight: 600, fontSize: 14 }} className="tabular">{s} persona</span>
              {editingPrice[s] !== undefined ? (
                <div style={{ display: 'flex', gap: 6 }}>
                  <input className="input" type="number" step="0.01" autoFocus
                    value={editingPrice[s]}
                    onChange={e => setEditingPrice(ep => ({ ...ep, [s]: e.target.value }))}
                    onKeyDown={e => {
                      if (e.key === 'Enter') commitPrice(s, editingPrice[s]);
                      if (e.key === 'Escape') setEditingPrice(ep => { const next = { ...ep }; delete next[s]; return next; });
                    }}
                    style={{ height: 36 }}
                  />
                  <button className="btn sm" onClick={() => commitPrice(s, editingPrice[s])}>
                    <IconCheck size={13} color="var(--cream)" />
                  </button>
                </div>
              ) : (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span className="tabular display" style={{ fontSize: 15, fontWeight: 600 }}>
                    {basePrices[s] != null ? window.formatEURP(basePrices[s]) : '—'}
                  </span>
                  <button className="icon-btn" style={{ width: 26, height: 26 }}
                    onClick={() => setEditingPrice(ep => ({ ...ep, [s]: basePrices[s] ?? '' }))}>
                    <IconEdit size={13} />
                  </button>
                </div>
              )}
              <button onClick={() => removePersonRow(s)} className="icon-btn" style={{ width: 30, height: 30, justifySelf: 'center' }}>
                <IconX size={13} />
              </button>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <input className="input" type="number" min="1" placeholder="Persona"
            value={newSize} onChange={e => setNewSize(e.target.value)}
            style={{ width: 120 }}
          />
          <div style={{ position: 'relative', width: 140 }}>
            <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-mute)', pointerEvents: 'none' }}>€</span>
            <input className="input" type="number" step="0.01" placeholder="Çmimi"
              value={newPrice} onChange={e => setNewPrice(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addPersonRow()}
              style={{ paddingLeft: 26 }}
            />
          </div>
          <button className="btn" disabled={!newSize || !newPrice} onClick={addPersonRow}>
            <IconPlus size={15} color="var(--cream)" /> Shto rresht
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Baklava pricing ────────────────────────────────────────────────────────

function BaklavaSettings({ baklavaPricing, setBaklavaPricing, addToast }) {
  const [tepsi, setTepsi] = React.useState(String(baklavaPricing.tepsi));
  const [kg, setKg] = React.useState(String(baklavaPricing.kg));

  const save = () => {
    const t = parseFloat(tepsi);
    const k = parseFloat(kg);
    if (isNaN(t) || t <= 0 || isNaN(k) || k <= 0) {
      addToast('Çmimet duhet të jenë numra pozitivë');
      return;
    }
    Promise.all([
      window.api.updateSetting('baklava_tepsi_price', t),
      window.api.updateSetting('baklava_kg_price', k),
    ]).then(() => {
      setBaklavaPricing({ tepsi: t, kg: k });
      addToast('Çmimet e bakllava u ruajtën');
    }).catch(err => addToast(err.message || 'Dështoi ruajtja'));
  };

  return (
    <div>
      <SectionHeader
        title="Çmimet e bakllava"
        subtitle="Çmimi bazë i përdorur kur krijohet një porosi bakllava të re."
      />
      <div className="card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 14 }}>
          <div className="field">
            <label className="field-label">Çmimi i një tepsi</label>
            <div style={{ position: 'relative' }}>
              <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-mute)', pointerEvents: 'none' }}>€</span>
              <input className="input" type="number" step="0.5" min="0" value={tepsi}
                onChange={e => setTepsi(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && save()}
                style={{ paddingLeft: 26 }} />
            </div>
            <span className="muted" style={{ fontSize: 12 }}>Shitet e tërë, si tepsi</span>
          </div>
          <div className="field">
            <label className="field-label">Çmimi për kg</label>
            <div style={{ position: 'relative' }}>
              <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-mute)', pointerEvents: 'none' }}>€</span>
              <input className="input" type="number" step="0.5" min="0" value={kg}
                onChange={e => setKg(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && save()}
                style={{ paddingLeft: 26 }} />
            </div>
            <span className="muted" style={{ fontSize: 12 }}>Shitet me kilogram</span>
          </div>
        </div>

        <div className="card-warm" style={{ padding: '10px 14px', fontSize: 13.5 }}>
          <span className="muted" style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Shembull · </span>
          1 tepsi = <strong>€{tepsi || '—'}</strong> &nbsp;·&nbsp; 1 kg = <strong>€{kg || '—'}</strong> &nbsp;·&nbsp; 0.5 kg = <strong>€{isNaN(parseFloat(kg)) ? '—' : (parseFloat(kg) * 0.5).toFixed(2)}</strong>
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button className="btn" onClick={save}>
            <IconCheck size={15} color="var(--cream)" /> Ruaj çmimet
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Backup ────────────────────────────────────────────────────────────────

function BackupSettings({ addToast }) {
  const [downloading, setDownloading] = React.useState(false);

  const doBackup = async () => {
    setDownloading(true);
    try {
      await window.api.downloadBackup();
      addToast('Backup u shkarkua');
    } catch (e) {
      addToast(e.message || 'Backup dështoi');
    } finally {
      setDownloading(false);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader
        title="Backup & eksporti"
        subtitle="Shkarko të gjitha të dhënat si skedar JSON — porosi, staf, imazhe dhe cilësime."
      />

      <div className="card">
        <div style={{ display: 'flex', gap: 18, alignItems: 'flex-start', flexWrap: 'wrap' }}>
          <div style={{ width: 52, height: 52, borderRadius: 14, background: 'var(--cream-2)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <IconDownload size={24} color="var(--ink)" />
          </div>
          <div style={{ flex: 1, minWidth: 220 }}>
            <h3 className="display" style={{ margin: '0 0 6px', fontSize: 18, fontWeight: 600 }}>Shkarko backup të plotë</h3>
            <p className="muted" style={{ margin: '0 0 16px', fontSize: 13.5, lineHeight: 1.6 }}>
              Eksporton të gjitha porositë, stafin, shijëtë, korrigjimet dhe cilësimet në një skedar <strong>.json</strong>.
              Imazhet janë të ngulitura si base64 — skedari është i plotë dhe nuk varet nga URL-të e serverit.
            </p>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 16 }}>
              {[
                'Të gjitha porositë',
                'Imazhe (base64)',
                'Stafi',
                'Shijët',
                'Cilësimet',
                'Korrigjimet AI',
                'Njoftimet',
              ].map(label => (
                <span key={label} style={{
                  fontSize: 12, fontWeight: 500, padding: '4px 10px',
                  background: 'var(--cream-2)', border: '1px solid var(--line)', borderRadius: 999,
                  color: 'var(--ink-2)',
                }}>{label}</span>
              ))}
            </div>
            <button className="btn" onClick={doBackup} disabled={downloading}>
              {downloading
                ? <><span className="spinner" style={{ width: 14, height: 14, borderColor: 'rgba(255,255,255,0.3)', borderTopColor: 'white' }} /> Duke shkarkuar…</>
                : <><IconDownload size={16} color="var(--cream)" /> Shkarko backup</>}
            </button>
          </div>
        </div>
      </div>

      <div className="card-warm" style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <IconAlertCircle size={16} color="var(--ink-2)" style={{ flexShrink: 0, marginTop: 2 }} />
        <p className="muted" style={{ margin: 0, fontSize: 13, lineHeight: 1.55 }}>
          Skedari JSON mund të jetë i madh nëse ka shumë imazhe. Ruajeni në një vend të sigurt — përmban të dhëna të klientëve. Ky backup nuk restaurohet automatikisht; është menduar si arkivim manual.
        </p>
      </div>
    </div>
  );
}

// ── Fridge settings ────────────────────────────────────────────────────────

function FridgeSettings({ fridgeConfig, setFridgeConfig, addToast }) {
  const [newName, setNewName] = React.useState('');

  const toggleMultiFridge = async () => {
    const next = !fridgeConfig.multiFridge;
    try {
      await window.api.updateSetting('multi_fridge_enabled', next ? '1' : '0');
      setFridgeConfig({ ...fridgeConfig, multiFridge: next });
      addToast(next ? 'Suporti për shumë frigorifer u aktivizua' : 'U kthye te numërimet standarde 1–8');
    } catch { addToast('Gabim gjatë ruajtjes'); }
  };

  const saveFridges = async (nextFridges) => {
    try {
      await window.api.updateSetting('fridges', JSON.stringify(nextFridges));
      setFridgeConfig({ ...fridgeConfig, fridges: nextFridges });
    } catch { addToast('Gabim gjatë ruajtjes'); }
  };

  const addFridge = async () => {
    const name = newName.trim();
    if (!name || fridgeConfig.fridges.includes(name)) return;
    await saveFridges([...fridgeConfig.fridges, name]);
    setNewName('');
    addToast(`Frigoriferi "${name}" u shtua`);
  };

  const removeFridge = async (name) => {
    await saveFridges(fridgeConfig.fridges.filter(f => f !== name));
    addToast(`Frigoriferi "${name}" u hoq`);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader
        title="Frigorifere"
        subtitle="Kontrollo si u caktohet frigorifer porosive të gatshme."
      />

      <div className="card">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 20 }}>
          <div style={{ flex: 1, minWidth: 200 }}>
            <h3 className="display" style={{ margin: '0 0 4px', fontSize: 18, fontWeight: 600 }}>Suport për shumë frigorifer</h3>
            <p className="muted" style={{ margin: 0, fontSize: 13, lineHeight: 1.5 }}>
              Kur është aktiv, mund të krijoni frigorifer me emra. Kur është joaktiv, stafi zgjedh nga numrat 1–8.
            </p>
          </div>
          <Toggle on={fridgeConfig.multiFridge} onChange={toggleMultiFridge} />
        </div>
      </div>

      {fridgeConfig.multiFridge && (
        <div className="card">
          <h3 className="display" style={{ margin: '0 0 6px', fontSize: 18, fontWeight: 600 }}>Frigoriferet e konfiguruara</h3>
          <p className="muted" style={{ margin: '0 0 16px', fontSize: 13 }}>Shtoni frigorifer me emra. Stafi do të zgjedhë nga këta kur cakton porosinë.</p>

          <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
            <input
              className="input"
              placeholder="p.sh. Frigorifer A, Kati 1…"
              value={newName}
              onChange={e => setNewName(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addFridge()}
            />
            <button className="btn" disabled={!newName.trim()} onClick={addFridge}>
              <IconPlus size={16} color="var(--cream)" /> Shto
            </button>
          </div>

          {fridgeConfig.fridges.length === 0 ? (
            <p className="muted" style={{ margin: 0, fontSize: 13, fontStyle: 'italic' }}>
              Asnjë frigorifer i konfiguruar akoma. Stafi nuk do mund të caktojë frigorifer derisa të shtoni të paktën një.
            </p>
          ) : (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {fridgeConfig.fridges.map(name => (
                <div key={name} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  padding: '8px 6px 8px 14px',
                  background: 'white', border: '1px solid var(--line)', borderRadius: 999,
                  fontSize: 14, fontWeight: 500,
                }}>
                  ❄ {name}
                  <button onClick={() => removeFridge(name)} className="icon-btn" style={{ width: 24, height: 24 }}>
                    <IconX size={12} />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function RollbackSettings({ addToast }) {
  const [snapshots, setSnapshots] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [selected, setSelected] = React.useState(null);
  const [preview, setPreview] = React.useState(null); // { orders: N } | { error: '...' } | null
  const [previewing, setPreviewing] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [unavailable, setUnavailable] = React.useState(false);

  const load = () => {
    setLoading(true);
    window.api.getSnapshots()
      .then(({ snapshots: s, unavailable: u }) => {
        if (u) { setUnavailable(true); return; }
        setSnapshots(s);
      })
      .catch(() => addToast('Gabim gjatë ngarkimit të kopjeve'))
      .finally(() => setLoading(false));
  };

  const doPreview = () => {
    setPreviewing(true);
    setPreview(null);
    window.api.previewSnapshot(selected.generation, selected.created)
      .then(data => setPreview(data))
      .catch(err => setPreview({ error: err.message || 'Gabim i panjohur' }))
      .finally(() => setPreviewing(false));
  };

  const doRollback = () => {
    setBusy(true);
    window.api.rollbackToSnapshot(selected.generation, selected.created)
      .then(() => setDone(true))
      .catch(err => { addToast('Gabim gjatë riktthimit: ' + (err.message || '')); setBusy(false); });
  };

  const fmtDate = (iso) => {
    try { return new Date(iso).toLocaleString('sq-AL', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit', second: '2-digit' }); }
    catch { return iso; }
  };
  const fmtSize = (b) => b >= 1024 ? `${(b / 1024).toFixed(1)} KB` : `${b} B`;
  const selKey = (s) => s ? `${s.generation}:${s.created}:${s.offset}` : '';

  return (
    <div className="card" style={{ padding: '18px 20px', border: '1px solid rgba(30,90,160,0.25)', background: 'rgba(30,90,160,0.04)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontWeight: 600, fontSize: 15, color: '#1e5aa0', marginBottom: 4 }}>Riktho nga kopje rezervë (R2)</div>
          <div className="muted" style={{ fontSize: 13, lineHeight: 1.5 }}>
            Zgjidhni një pikë, klikoni <strong>Kontrollo</strong> për të parë sa porosi ka — pa ndryshuar asgjë.
          </div>
        </div>
        {snapshots === null && !unavailable && (
          <button className="btn secondary" onClick={load} disabled={loading} style={{ whiteSpace: 'nowrap', flexShrink: 0 }}>
            {loading ? 'Duke ngarkuar…' : 'Shiko kopjet'}
          </button>
        )}
      </div>

      {unavailable && (
        <p style={{ marginTop: 14, fontSize: 13, color: 'var(--ink-mute)' }}>Litestream nuk është i konfiguruar në këtë mjedis.</p>
      )}

      {done && (
        <div style={{ marginTop: 16, padding: '12px 16px', background: 'rgba(30,90,160,0.08)', borderRadius: 10, fontSize: 14, color: '#1e5aa0', fontWeight: 500 }}>
          Riktthimi u krye. Aplikacioni po rindizet — rifresko pas 10–15 sekondave.
        </div>
      )}

      {snapshots !== null && !done && (
        <div style={{ marginTop: 16 }}>
          {snapshots.length === 0 ? (
            <p style={{ fontSize: 13, color: 'var(--ink-mute)' }}>Nuk u gjet asnjë kopje në R2.</p>
          ) : (
            <>
              <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginBottom: 8 }}>
                Shënime të mëdha <span style={{ color: '#b94000', fontWeight: 600 }}>⚠</span> mund të jenë fshirje. Kontrolloni para se të riktheni.
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                {snapshots.map((s) => {
                  const active = selKey(selected) === selKey(s);
                  const big = s.size > 1000;
                  return (
                    <button key={selKey(s)} onClick={() => { setSelected(active ? null : s); setPreview(null); }}
                      style={{
                        textAlign: 'left', padding: '8px 12px', borderRadius: 8, border: '1px solid',
                        borderColor: active ? '#1e5aa0' : big ? 'rgba(185,64,0,0.35)' : 'var(--line)',
                        background: active ? 'rgba(30,90,160,0.07)' : big ? 'rgba(185,64,0,0.04)' : 'white',
                        cursor: 'pointer', fontSize: 12,
                        display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8,
                      }}>
                      <span style={{ fontWeight: active ? 600 : 400 }}>{fmtDate(s.created)}</span>
                      <span style={{ color: big ? '#b94000' : 'var(--ink-mute)', fontWeight: big ? 600 : 400 }}>
                        {big ? '⚠ ' : ''}{fmtSize(s.size)}
                      </span>
                    </button>
                  );
                })}
              </div>

              {selected && (
                <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(30,90,160,0.15)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                    <button className="btn secondary" onClick={doPreview} disabled={previewing || busy}
                      style={{ height: 36, padding: '0 16px', fontSize: 13 }}>
                      {previewing ? 'Duke kontrolluar…' : 'Kontrollo'}
                    </button>
                    {preview && (
                      <span style={{ fontSize: 13, fontWeight: 600,
                        color: preview.error ? '#8c2e2e' : preview.orders > 0 ? '#1a6e1a' : '#8c2e2e' }}>
                        {preview.error
                          ? `Gabim: ${preview.error}`
                          : preview.orders > 0
                            ? `✓ ${preview.orders} porosi gjenden`
                            : '✗ Asnjë porosi — provo një tjetër'}
                      </span>
                    )}
                  </div>

                  {preview?.orders > 0 && (
                    <div style={{ marginTop: 12 }}>
                      <p style={{ margin: '0 0 10px', fontSize: 13, fontWeight: 600, color: '#8c2e2e' }}>
                        Të dhënat aktuale do të zëvendësohen. Ky veprim nuk mund të kthyhet mbrapsht.
                      </p>
                      <div style={{ display: 'flex', gap: 10 }}>
                        <button className="btn" onClick={doRollback} disabled={busy}
                          style={{ background: '#1e5aa0', borderColor: '#1e5aa0' }}>
                          {busy ? 'Duke rikthyer…' : 'Po, riktho tani'}
                        </button>
                        <button className="chip" onClick={() => { setSelected(null); setPreview(null); setSnapshots(null); }}
                          style={{ height: 40, padding: '0 18px' }} disabled={busy}>
                          Anulo
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
}

function DangerSettings({ addToast, onOrdersCleared, onCorrectionsCleared, setBaklavaPricing, setPricingConfig }) {
  const [confirm, setConfirm] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [confirmCorr, setConfirmCorr] = React.useState(false);
  const [busyCorr, setBusyCorr] = React.useState(false);
  const [confirmFin, setConfirmFin] = React.useState(false);
  const [busyFin, setBusyFin] = React.useState(false);
  const [rollbackEnabled, setRollbackEnabled] = React.useState(false);

  React.useEffect(() => {
    window.api.rollbackEnabled().then(({ enabled }) => setRollbackEnabled(enabled)).catch(() => {});
  }, []);

  const clearAll = () => {
    setBusy(true);
    window.api.clearAllOrders()
      .then(({ deleted }) => {
        onOrdersCleared();
        addToast(`U fshinë ${deleted} porosi`);
        setConfirm(false);
      })
      .catch(() => addToast('Gabim gjatë fshirjes'))
      .finally(() => setBusy(false));
  };

  const clearCorrections = () => {
    setBusyCorr(true);
    window.api.clearAllCorrections()
      .then(({ deleted }) => {
        onCorrectionsCleared();
        addToast(`U fshinë ${deleted} korrigjime`);
        setConfirmCorr(false);
      })
      .catch(() => addToast('Gabim gjatë fshirjes'))
      .finally(() => setBusyCorr(false));
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {rollbackEnabled && <RollbackSettings addToast={addToast} />}

      <div className="card" style={{ padding: '18px 20px', border: '1px solid rgba(140,46,46,0.25)', background: 'rgba(140,46,46,0.04)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 15, color: '#8c2e2e', marginBottom: 4 }}>Fshi të gjitha porositë</div>
            <div className="muted" style={{ fontSize: 13, lineHeight: 1.5 }}>
              Fshin çdo porosi nga baza e të dhënave. Ky veprim nuk mund të kthyhet mbrapsht.
            </div>
          </div>
          <button className="btn" onClick={() => setConfirm(true)}
            style={{ background: '#8c2e2e', borderColor: '#8c2e2e', whiteSpace: 'nowrap', flexShrink: 0 }}>
            <IconTrash size={14} color="white" /> Fshi të gjitha
          </button>
        </div>

        {confirm && (
          <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid rgba(140,46,46,0.2)' }}>
            <p style={{ margin: '0 0 14px', fontWeight: 600, fontSize: 14, color: '#8c2e2e' }}>
              Je i sigurt? Të gjitha porositë do të fshihen përgjithmonë.
            </p>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="btn" onClick={clearAll} disabled={busy}
                style={{ background: '#8c2e2e', borderColor: '#8c2e2e' }}>
                {busy ? 'Duke fshirë…' : 'Po, fshi të gjitha'}
              </button>
              <button className="chip" onClick={() => setConfirm(false)} disabled={busy}
                style={{ height: 40, padding: '0 18px' }}>
                Anulo
              </button>
            </div>
          </div>
        )}
      </div>

      <div className="card" style={{ padding: '18px 20px', border: '1px solid rgba(140,46,46,0.25)', background: 'rgba(140,46,46,0.04)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 15, color: '#8c2e2e', marginBottom: 4 }}>Fshi të gjitha parashikimet AI</div>
            <div className="muted" style={{ fontSize: 13, lineHeight: 1.5 }}>
              Fshin historikun e korrigjimeve të parashikimeve. Ky veprim nuk mund të kthyhet mbrapsht.
            </div>
          </div>
          <button className="btn" onClick={() => setConfirmCorr(true)}
            style={{ background: '#8c2e2e', borderColor: '#8c2e2e', whiteSpace: 'nowrap', flexShrink: 0 }}>
            <IconTrash size={14} color="white" /> Fshi parashikimet
          </button>
        </div>

        {confirmCorr && (
          <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid rgba(140,46,46,0.2)' }}>
            <p style={{ margin: '0 0 14px', fontWeight: 600, fontSize: 14, color: '#8c2e2e' }}>
              Je i sigurt? Të gjitha korrigjimet do të fshihen përgjithmonë.
            </p>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="btn" onClick={clearCorrections} disabled={busyCorr}
                style={{ background: '#8c2e2e', borderColor: '#8c2e2e' }}>
                {busyCorr ? 'Duke fshirë…' : 'Po, fshi të gjitha'}
              </button>
              <button className="chip" onClick={() => setConfirmCorr(false)} disabled={busyCorr}
                style={{ height: 40, padding: '0 18px' }}>
                Anulo
              </button>
            </div>
          </div>
        )}
      </div>

      <div className="card" style={{ padding: '18px 20px', border: '1px solid rgba(140,46,46,0.25)', background: 'rgba(140,46,46,0.04)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 15, color: '#8c2e2e', marginBottom: 4 }}>Fshi të dhënat financiare</div>
            <div className="muted" style={{ fontSize: 13, lineHeight: 1.5 }}>
              Fshin çmimin, depozitën dhe të gjitha të dhënat e pagesës nga porositë, si dhe çmimet e konfigurimit (bakllava). Porositë mbeten të paprekura.
            </div>
          </div>
          <button className="btn" onClick={() => setConfirmFin(true)}
            style={{ background: '#8c2e2e', borderColor: '#8c2e2e', whiteSpace: 'nowrap', flexShrink: 0 }}>
            <IconTrash size={14} color="white" /> Fshi financiaret
          </button>
        </div>

        {confirmFin && (
          <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid rgba(140,46,46,0.2)' }}>
            <p style={{ margin: '0 0 14px', fontWeight: 600, fontSize: 14, color: '#8c2e2e' }}>
              Je i sigurt? Çmimet dhe pagesat do të fshihen nga të gjitha porositë.
            </p>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="btn" onClick={() => {
                setBusyFin(true);
                window.api.clearFinancialData()
                  .then(({ updated }) => {
                    setBaklavaPricing({ tepsi: 0, kg: 0 });
                    setPricingConfig(prev => ({
                      ...prev,
                      basePrices: Object.fromEntries(Object.keys(prev.basePrices).map(k => [k, 0])),
                    }));
                    addToast(`U pastruan ${updated} porosi`);
                    setConfirmFin(false);
                  })
                  .catch(() => addToast('Gabim gjatë fshirjes'))
                  .finally(() => setBusyFin(false));
              }} disabled={busyFin} style={{ background: '#8c2e2e', borderColor: '#8c2e2e' }}>
                {busyFin ? 'Duke fshirë…' : 'Po, fshi financiaret'}
              </button>
              <button className="chip" onClick={() => setConfirmFin(false)} disabled={busyFin}
                style={{ height: 40, padding: '0 18px' }}>
                Anulo
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      width: 46, height: 26, borderRadius: 999,
      background: on ? 'var(--green)' : 'var(--cream-3)',
      position: 'relative', border: 'none', cursor: 'pointer',
      transition: 'background 150ms ease', padding: 0,
    }}>
      <span style={{
        position: 'absolute', top: 3, left: on ? 23 : 3,
        width: 20, height: 20, borderRadius: '50%', background: 'white',
        transition: 'left 150ms ease',
        boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
      }} />
    </button>
  );
}

Object.assign(window, { SettingsScreen });
