// ViG Command Center — Settings hub (appearance, data, integrations, about)
const { useState: useStateSE, useEffect: useEffectSE } = React;

function SettingsPage({ go, dark, setDark, role }) {
  const [msg, setMsg] = useStateSE('');
  const [confirmReset, setConfirmReset] = useStateSE(false);

  // count what's stored
  const stored = (() => {
    let n = 0, bytes = 0;
    try { for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && k.startsWith('vig2_')) { n++; bytes += (localStorage.getItem(k) || '').length; } } } catch (e) {}
    return { n, kb: (bytes / 1024).toFixed(1) };
  })();

  const exportAll = () => {
    const dump = {};
    try { for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && k.startsWith('vig2_')) dump[k] = localStorage.getItem(k); } } catch (e) {}
    const blob = new Blob([JSON.stringify({ _app: 'ViG Command Center', _exported: new Date().toISOString(), data: dump }, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'vig-command-center-backup.json'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 2000);
    setMsg('Backup downloaded — keep it safe to restore your data later.');
  };
  // Alliance Share Code — compact roster snapshot others can import (no backend)
  const genShareCode = () => {
    try {
      const own = LS.get('vig2_ownership', {});
      const owned = Object.keys(own).filter(k => own[k]);
      const payload = { v: 1, t: Date.now(), o: owned };
      const code = btoa(unescape(encodeURIComponent(JSON.stringify(payload))));
      navigator.clipboard && navigator.clipboard.writeText(code);
      setMsg('Share code copied (' + owned.length + ' generals). Send it to your alliance — they paste it under "Import share code".');
    } catch (e) { setMsg('Could not generate share code.'); }
  };
  const importShareCode = () => {
    const code = prompt('Paste an alliance share code to import that roster:');
    if (!code) return;
    try {
      const p = JSON.parse(decodeURIComponent(escape(atob(code.trim()))));
      if (!p.o || !Array.isArray(p.o)) throw 0;
      const own = {}; p.o.forEach(k => own[k] = true);
      LS.set('vig2_ownership', own);
      setMsg('Imported ' + p.o.length + ' generals from share code. Reloading…');
      setTimeout(() => location.reload(), 900);
    } catch (e) { setMsg('That share code is invalid or corrupted.'); }
  };
  const importAll = (file) => {
    const r = new FileReader();
    r.onload = () => { try { const j = JSON.parse(r.result); const d = j.data || j; let n = 0; Object.entries(d).forEach(([k, v]) => { if (k.startsWith('vig2_')) { localStorage.setItem(k, v); n++; } }); setMsg(`Restored ${n} settings. Reloading…`); setTimeout(() => location.reload(), 900); } catch (e) { setMsg('That file could not be read — make sure it is a ViG backup JSON.'); } };
    r.readAsText(file);
  };
  const resetAll = () => {
    try { const keys = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && k.startsWith('vig2_') && k !== 'vig2_session' && k !== 'vig2_users') keys.push(k); } keys.forEach(k => localStorage.removeItem(k)); } catch (e) {}
    setMsg('All progress reset to defaults. Reloading…'); setTimeout(() => location.reload(), 900);
  };

  const Row = ({ title, desc, children }) => (
    <div className="flex flex-wrap items-center gap-3 border-b border-zinc-50 px-4 py-3.5 last:border-0 dark:border-zinc-800/60">
      <div className="min-w-0 flex-1"><div className="text-[13.5px] font-semibold text-zinc-900 dark:text-white">{title}</div>{desc && <div className="text-[11.5px] text-zinc-400">{desc}</div>}</div>
      {children}
    </div>
  );
  const Section = ({ icon, title, children }) => (
    <Card className="overflow-hidden">
      <div className="flex items-center gap-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800"><Icon name={icon} size={16} className="text-brand" /><span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">{title}</span></div>
      <div>{children}</div>
    </Card>
  );
  const btn = 'inline-flex items-center gap-1.5 rounded-lg border border-zinc-200 px-3 py-2 text-[12.5px] font-semibold text-zinc-600 transition-colors hover:border-brand hover:text-brand dark:border-zinc-700 dark:text-zinc-300';

  return (
    <div className="mx-auto max-w-2xl space-y-4">
      {msg && <div className="rounded-lg bg-emerald-50 px-3 py-2 text-[12.5px] text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300">{msg}</div>}

      <Section icon="bolt" title="Appearance">
        <Row title="Theme" desc="Night mode is the command-center default">
          <div className="flex gap-1">
            <button onClick={() => setDark(true)} className={`rounded-lg border px-3 py-1.5 text-[12px] font-semibold ${dark ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-400 dark:border-zinc-700'}`}>🌙 Night</button>
            <button onClick={() => setDark(false)} className={`rounded-lg border px-3 py-1.5 text-[12px] font-semibold ${!dark ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-400 dark:border-zinc-700'}`}>☀️ Day</button>
          </div>
        </Row>
        <Row title="Command palette" desc="Jump to anything — press ⌘K / Ctrl+K anywhere"><kbd className="rounded border border-zinc-200 px-2 py-1 text-[11px] font-semibold text-zinc-400 dark:border-zinc-700">⌘K</kbd></Row>
        <Row title="Replay onboarding tour" desc="See the guided walkthrough again"><button className={btn} onClick={() => { LS.set('vig2_onboarded', false); location.reload(); }}><Icon name="target" size={13} />Replay</button></Row>
      </Section>

      <Section icon="grid" title="Integrations & sync">
        <Row title="Discord" desc="Auto-post briefings, alerts & digests to your channel"><button className={btn} onClick={() => go('discord')}><Icon name="chat" size={13} />Configure</button></Row>
        <Row title="Live alliance sync" desc="Pull VIG / RSP / NEF standings, auto-refresh every 24h"><button className={btn} onClick={() => go('warroom')}><Icon name="trophy" size={13} />War Room</button></Row>
        {role === 'Admin' && <Row title="User management" desc="Add members & assign roles"><button className={btn} onClick={() => go('users')}><Icon name="shield" size={13} />Manage</button></Row>}
      </Section>

      <Section icon="database" title="Your data">
        {window.CloudSyncPanel && <div style={{ marginBottom: '1rem' }}><CloudSyncPanel /></div>}
        <Row title="Alliance share code" desc="Generate a code to share your roster — alliance-mates paste it to sync"><div className="flex gap-1.5"><button className={btn} onClick={genShareCode}><Icon name="link" size={13} />Copy code</button><button className={btn} onClick={importShareCode}><Icon name="reset" size={13} />Import code</button></div></Row>
        <Row title="Backup all data" desc={`${stored.n} settings stored on this device · ${stored.kb} KB`}><button className={btn} onClick={exportAll}><Icon name="download" size={13} />Export</button></Row>
        <Row title="Restore from backup" desc="Load a previously exported ViG backup file">
          <label className={btn + ' cursor-pointer'}><Icon name="reset" size={13} />Import<input type="file" accept="application/json" className="hidden" onChange={e => e.target.files[0] && importAll(e.target.files[0])} /></label>
        </Row>
        <Row title="Reset progress" desc="Clears ownership, settings & history (keeps your account & members)">
          {confirmReset ? (
            <div className="flex gap-1.5"><button onClick={resetAll} className="rounded-lg bg-rose-500 px-3 py-2 text-[12px] font-semibold text-white hover:brightness-110">Confirm reset</button><button onClick={() => setConfirmReset(false)} className={btn}>Cancel</button></div>
          ) : <button onClick={() => setConfirmReset(true)} className="inline-flex items-center gap-1.5 rounded-lg border border-rose-200 px-3 py-2 text-[12.5px] font-semibold text-rose-500 hover:bg-rose-50 dark:border-rose-900/50 dark:hover:bg-rose-950/30"><Icon name="x" size={13} />Reset</button>}
        </Row>
      </Section>

      <Section icon="star" title="About">
        <div className="px-4 py-4">
          <div className="flex items-center gap-3">
            <div className="glow-mark flex h-11 w-11 items-center justify-center rounded-xl bg-brand text-[20px] font-extrabold text-white">V</div>
            <div><div className="text-[15px] font-bold text-zinc-900 dark:text-white">ViG Command Center</div><div className="text-[11.5px] text-zinc-400">Version 2.0 · Server 428</div></div>
          </div>
          <div className="mt-3 grid grid-cols-3 gap-2 text-center">
            {[['176', 'Generals'], ['75', 'Covenants'], ['17', 'Dragons'], ['30+', 'Modules'], ['8', 'Calculators'], ['5', 'Automations']].map(([n, l]) => (
              <div key={l} className="rounded-lg border border-zinc-100 py-2 dark:border-zinc-800"><div className="text-[16px] font-bold text-brand">{n}</div><div className="text-[10px] uppercase tracking-wide text-zinc-400">{l}</div></div>
            ))}
          </div>
          <p className="mt-3 text-[11.5px] text-zinc-400">The definitive Evony intelligence platform — guides, analytics, AI, alliance intelligence, calculators, planning &amp; community in one connected ecosystem. All data stays on your device.</p>
        </div>
      </Section>
    </div>
  );
}
window.SettingsPage = SettingsPage;
