/* Nutri Settings Screen
   - Account section: photo, displayName, email, edit name, logout, sync status
   - Appearance: light/dark toggle
   - Backup: export/import (writes/reads under current uid)
   - Migration from old Calories Analysis
   - Reset all of MY data (does not touch other users)
*/

function SettingsScreen() {
  const auth = useAuth();
  const store = useStore();
  const [msg, setMsg] = React.useState(null);
  const [editingName, setEditingName] = React.useState(false);
  const [nameDraft, setNameDraft] = React.useState('');

  const profile = store.profile() || {};
  const user = auth.user || {};
  const displayName = profile.displayName || user.displayName || '';
  const email = profile.email || user.email || '';
  const photoURL = profile.photoURL || user.photoURL || '';

  const meals = store.meals().length;
  const finance = store.finance().length;
  const goals = store.goals().length;
  const diary = store.diary().length;

  const syncStatus = store.syncStatus();
  const syncError = store.syncError();
  const lastSync = store.lastSyncAt();

  function flash(kind, text) {
    setMsg({ kind, text });
    setTimeout(() => setMsg(null), 4500);
  }

  async function checkForUpdates() {
    try {
      const res = await fetch('/version.json?_=' + Date.now(), { cache: 'no-store' });
      if (!res.ok) throw new Error('HTTP ' + res.status);
      const data = await res.json();
      const current = window.__NUTRI_VERSION || '?';
      if (data.version && data.version !== current) {
        flash('ok', 'Update available — v' + data.version + '. Refresh to apply.');
      } else {
        flash('ok', 'You\'re up to date (v' + current + ')');
      }
    } catch (e) {
      flash('err', 'Could not check for updates. Are you online?');
    }
  }

  function startEditName() {
    setNameDraft(displayName);
    setEditingName(true);
  }
  async function saveName() {
    const v = (nameDraft || '').trim();
    if (!v) { setEditingName(false); return; }
    try {
      await store.updateDisplayName(v);
      flash('ok', 'Display name updated.');
    } catch (e) { flash('err', 'Could not save: ' + (e.message || e)); }
    setEditingName(false);
  }

  async function onLogout() {
    if (!confirm('Sign out of Nutri? Your data stays safe in the cloud.')) return;
    try { await auth.signOut(); }
    catch (e) { flash('err', 'Logout failed: ' + (e.message || e)); }
  }

  function onExport() {
    try { store.exportBackup(); flash('ok', 'Backup downloaded.'); }
    catch (e) { flash('err', 'Export failed: ' + e.message); }
  }

  function handleFile(ev, kind) {
    const file = ev.target.files && ev.target.files[0];
    ev.target.value = '';
    if (!file) return;
    if (!store.uid()) { flash('err', 'Sign in first.'); return; }
    if (!confirm(`Replace ALL of YOUR Nutri data with the contents of "${file.name}"?\n\nThis only changes your account. Export a backup first if you want to keep your current data.`)) return;
    flash('ok', 'Reading file…');
    const reader = new FileReader();
    reader.onload = async () => {
      try {
        const payload = JSON.parse(reader.result);
        const result = kind === 'migrate'
          ? await store.migrateFromCaloriesAnalysis(payload)
          : await store.importBackup(payload);
        if (result.ok) {
          const s = result.stats || {};
          flash('ok', `${result.message} ${s.meals||0} meals · ${s.finance||0} txns · ${s.goals||0} goals · ${s.diary||0} memories.`);
        } else {
          flash('err', result.message);
        }
      } catch (e) {
        flash('err', 'Could not read file: ' + e.message);
      }
    };
    reader.onerror = () => flash('err', 'Could not read file.');
    reader.readAsText(file);
  }

  function onReset() {
    if (!confirm('Wipe ALL of your Nutri data (meals, finance, goals, diary, chat)? This cannot be undone. Export a backup first.')) return;
    store.resetAllData();
    flash('ok', 'Your data has been cleared.');
  }

  // styles
  const card = {
    background: 'var(--surface)', border: '1px solid var(--border)',
    borderRadius: 16, padding: 18, marginBottom: 14,
    boxShadow: 'var(--shadow-sm)',
  };
  const h = { fontSize: 14, fontWeight: 600, margin: '0 0 4px', letterSpacing: '-0.01em' };
  const sub = { fontSize: 12.5, color: 'var(--muted)', margin: '0 0 14px', lineHeight: 1.45 };
  const btn = {
    display: 'inline-flex', alignItems: 'center', gap: 8,
    padding: '10px 16px', borderRadius: 10,
    background: 'var(--text)', color: 'var(--bg)',
    border: 'none', fontSize: 13.5, fontWeight: 600, cursor: 'pointer',
    font: 'inherit',
  };
  const btnGhost = { ...btn, background: 'var(--surface-2)', color: 'var(--text)', border: '1px solid var(--border-2)' };
  const btnDanger = { ...btn, background: 'transparent', color: '#A33', border: '1px solid rgba(170,51,51,.3)' };

  return (
    <div style={{ padding: 16, paddingBottom: 100 }}>
      {/* Header */}
      <div style={{ marginBottom: 18, display: 'flex', alignItems: 'center', gap: 12 }}>
        <BrandMark size={42} radius={11}/>
        <div>
          <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', margin: '0 0 4px' }}>Settings</h1>
          <p style={{ fontSize: 13, color: 'var(--muted)', margin: 0 }}>Account, appearance, and data.</p>
        </div>
      </div>

      {/* Flash */}
      {msg && (
        <div style={{
          ...card, padding: '12px 14px', marginBottom: 14,
          borderColor: msg.kind === 'ok' ? 'rgba(79,168,98,.35)' : 'rgba(170,51,51,.35)',
          background: msg.kind === 'ok' ? 'var(--c-protein-soft)' : 'rgba(170,51,51,.07)',
          color: msg.kind === 'ok' ? 'var(--text)' : '#A33',
          fontSize: 13,
        }}>{msg.text}</div>
      )}

      {/* Account */}
      <div style={card}>
        <h3 style={h}>Account</h3>
        <p style={sub}>Signed in via Firebase. Your data lives at <code style={{ fontSize: 11.5, background: 'var(--surface-2)', padding: '1px 6px', borderRadius: 4 }}>users/{store.uid() || '…'}</code>.</p>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: 12, borderRadius: 12,
          background: 'var(--surface-2)', border: '1px solid var(--border)',
          marginBottom: 12,
        }}>
          <div style={{
            width: 52, height: 52, borderRadius: '50%',
            background: 'linear-gradient(135deg, #C6BFA8, #8C8669)',
            color: '#fff', display: 'grid', placeItems: 'center',
            fontSize: 18, fontWeight: 700, flexShrink: 0,
            overflow: 'hidden',
          }}>
            {photoURL
              ? <img src={photoURL} alt="avatar" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
              : (displayName || email || 'N').slice(0,2).toUpperCase()}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            {editingName ? (
              <div style={{ display: 'flex', gap: 6 }}>
                <input value={nameDraft} onChange={e=>setNameDraft(e.target.value)} autoFocus
                  onKeyDown={e=>{ if (e.key === 'Enter') saveName(); if (e.key === 'Escape') setEditingName(false); }}
                  style={{
                    flex: 1, padding: '6px 10px', borderRadius: 8,
                    background: 'var(--surface)', border: '1px solid var(--border-2)',
                    color: 'var(--text)', font: 'inherit', fontSize: 14,
                  }}/>
                <button onClick={saveName} style={{
                  padding: '6px 10px', borderRadius: 8,
                  background: 'var(--accent)', color: 'var(--on-accent)',
                  border: 'none', font: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                }}>Save</button>
              </div>
            ) : (
              <>
                <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em',
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {displayName || 'Friend'}
                </div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {email || '—'}
                </div>
              </>
            )}
          </div>
          {!editingName && (
            <button onClick={startEditName} style={{
              padding: '6px 10px', borderRadius: 999,
              background: 'var(--surface)', color: 'var(--text)',
              border: '1px solid var(--border-2)', font: 'inherit',
              fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
              flexShrink: 0,
            }}>Edit name</button>
          )}
        </div>

        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 12 }}>
          <SyncBadge status={syncStatus} error={syncError} lastSync={lastSync}/>
        </div>

        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={onLogout} style={btnDanger}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
            Log out
          </button>
        </div>
      </div>

      {/* Stats summary */}
      <div style={card}>
        <h3 style={h}>Your data</h3>
        <p style={sub}>Stored in Firestore — synced across your devices.</p>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Stat label="Meals" value={meals}/>
          <Stat label="Transactions" value={finance}/>
          <Stat label="Goals" value={goals}/>
          <Stat label="Memories" value={diary}/>
        </div>
      </div>

      {/* Appearance */}
      <div style={card}>
        <h3 style={h}>Appearance</h3>
        <p style={sub}>Switch between light and dark.</p>
        <ThemeToggle/>
      </div>

      {/* Notifications */}
      <div style={card}>
        <h3 style={h}>Notifications</h3>
        <p style={sub}>Daily reminders for your Diary “On This Day” and unfinished Goals. They fire while Nutri is open in your browser.</p>
        <NotificationsSettings store={store} flash={flash}/>
      </div>

      {/* Backup */}
      <div style={card}>
        <h3 style={h}>Backup</h3>
        <p style={sub}>
          Export everything (your meals, finance, goals, diary, assistant chat) to a single JSON file.
          Save it on your device, in cloud storage, or send it to yourself.
        </p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          <button style={btn} onClick={onExport}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
            Export backup
          </button>
          <label style={{ ...btnGhost, cursor: 'pointer' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
            Import backup
            <input type="file" accept=".json,application/json"
              style={{ display: 'none' }}
              onChange={(ev) => handleFile(ev, 'backup')}/>
          </label>
        </div>
      </div>

      {/* Migration */}
      <div style={card}>
        <h3 style={h}>Migrate from Calories Analysis</h3>
        <p style={sub}>
          Already have data in the older <code style={{ fontSize: 12, background: 'var(--surface-2)', padding: '1px 5px', borderRadius: 4 }}>Calories Analysis.html</code> site?
          {' '}Open that site, use its <strong>Save backup</strong> action to download the JSON,
          then pick that file here. We'll convert it into your current account.
        </p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          <label style={{ ...btnGhost, cursor: 'pointer' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
            Migrate data file
            <input type="file" accept=".json,application/json"
              style={{ display: 'none' }}
              onChange={(ev) => handleFile(ev, 'migrate')}/>
          </label>
        </div>
      </div>

      {/* Danger */}
      <div style={{ ...card, borderColor: 'rgba(170,51,51,.25)' }}>
        <h3 style={{ ...h, color: '#A33' }}>Wipe my data</h3>
        <p style={sub}>Clears all your meals, finance, goals, diary, and chat in this account. Logs you in afterward — but with nothing saved.</p>
        <button style={btnDanger} onClick={onReset}>Wipe all my Nutri data</button>
      </div>

      {/* App version + update check */}
      <div style={{ ...card, padding: '14px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600 }}>App Version</div>
          <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
            {window.__NUTRI_VERSION ? 'v' + window.__NUTRI_VERSION : '—'}
            <span style={{ marginLeft: 8, color: 'var(--border-2)' }}>·</span>
            <span style={{ marginLeft: 8, color: 'var(--muted)' }}>Nutri Lifestyle Tracker</span>
          </div>
        </div>
        <button onClick={checkForUpdates} style={{ ...btnGhost, fontSize: 12, padding: '5px 12px', whiteSpace: 'nowrap' }}>
          Check for update
        </button>
      </div>

      {/* QA / Diagnostics — developer panel (collapsed by default) */}
      <QAPanel card={card} h={h} sub={sub} btnGhost={btnGhost}/>
    </div>
  );
}

function SyncBadge({ status, error, lastSync }) {
  const cfg = {
    idle:    { label: 'In sync',  color: 'var(--c-protein)', dot: 'var(--c-protein)' },
    syncing: { label: 'Syncing…', color: 'var(--c-fat)',     dot: 'var(--c-fat)' },
    loading: { label: 'Loading…', color: 'var(--c-fat)',     dot: 'var(--c-fat)' },
    error:   { label: 'Sync error', color: '#A33',           dot: '#A33' },
    offline: { label: 'Offline',  color: 'var(--muted)',     dot: 'var(--muted-2)' },
  }[status] || { label: status, color: 'var(--muted)', dot: 'var(--muted-2)' };
  let when = '';
  if (lastSync) {
    const d = new Date(lastSync);
    const diff = Math.max(0, Date.now() - d.getTime());
    if (diff < 60_000) when = ' · just now';
    else if (diff < 3600_000) when = ' · ' + Math.round(diff / 60000) + 'm ago';
    else when = ' · ' + d.toLocaleString();
  }
  return (
    <div title={error || ''} style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '6px 12px', borderRadius: 999,
      background: 'var(--surface-2)', border: '1px solid var(--border-2)',
      fontSize: 11.5, fontWeight: 600, color: cfg.color,
    }}>
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: cfg.dot, display: 'inline-block' }}/>
      {cfg.label}{when}
    </div>
  );
}

function ThemeToggle() {
  const [theme, setTheme] = React.useState(() => document.body.getAttribute('data-theme') || 'light');
  React.useEffect(() => {
    const on = (e) => setTheme(e.detail);
    window.addEventListener('nutri:theme', on);
    return () => window.removeEventListener('nutri:theme', on);
  }, []);
  function pick(t) {
    setTheme(t);
    if (window.__nutriSetTheme) window.__nutriSetTheme(t);
  }
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4,
      background: 'var(--surface-2)', borderRadius: 12, padding: 4, border: '1px solid var(--border)',
    }}>
      {[
        { id: 'light', label: '☀️ Light' },
        { id: 'dark',  label: '🌙 Dark'  },
      ].map(o => (
        <button key={o.id} onClick={()=>pick(o.id)} style={{
          padding: '9px 0', borderRadius: 9, border: 0,
          background: theme === o.id ? 'var(--surface)' : 'transparent',
          color: theme === o.id ? 'var(--text)' : 'var(--muted)',
          fontSize: 13, fontWeight: 600, cursor: 'pointer', font: 'inherit',
          boxShadow: theme === o.id ? 'var(--shadow-sm)' : 'none',
        }}>{o.label}</button>
      ))}
    </div>
  );
}

function NotificationsSettings({ store, flash }) {
  const supported = typeof window !== 'undefined' && 'Notification' in window;
  const ns = store.notificationSettings();
  const [perm, setPerm] = React.useState(supported ? Notification.permission : 'unsupported');

  function requestPerm() {
    if (!supported) return;
    try {
      Notification.requestPermission().then(p => {
        setPerm(p);
        if (p === 'granted') { try { new Notification('Notifications enabled ✓', { body: 'Nutri will remind you here.', icon: './icon.png' }); } catch (_) {} flash && flash('ok', 'Notifications enabled.'); }
        else if (p === 'denied') flash && flash('err', 'Notifications blocked — allow them in your browser settings.');
      });
    } catch (_) {}
  }
  function set(section, key, value) { store.updateNotificationSetting(section, key, value); }

  if (!supported) {
    return <div style={{ fontSize: 12.5, color: 'var(--muted)', background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 10, padding: 12 }}>
      Your browser doesn’t support notifications. Everything else in Nutri works normally.
    </div>;
  }

  const permCfg = {
    granted: { label: 'Allowed', color: 'var(--c-protein)' },
    denied:  { label: 'Blocked', color: '#A33' },
    default: { label: 'Not set', color: 'var(--muted)' },
  }[perm] || { label: perm, color: 'var(--muted)' };

  const Toggle = ({ on, onClick }) => (
    <button onClick={onClick} aria-pressed={on} style={{
      width: 44, height: 26, borderRadius: 999, border: '1px solid ' + (on ? 'var(--accent)' : 'var(--border-2)'),
      background: on ? 'var(--accent)' : 'var(--surface-2)', position: 'relative', cursor: 'pointer', flexShrink: 0, padding: 0,
    }}>
      <span style={{ position: 'absolute', top: 2, left: on ? 20 : 2, width: 20, height: 20, borderRadius: '50%', background: on ? 'var(--on-accent)' : 'var(--muted)', transition: 'left .15s ease' }}/>
    </button>
  );
  const timeInput = { padding: '6px 10px', borderRadius: 8, background: 'var(--surface)', border: '1px solid var(--border-2)', font: 'inherit', fontSize: 13, color: 'var(--text)' };
  const secWrap = { background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 12, padding: 12, marginBottom: 10 };
  const rowSB = { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 };

  return (
    <div>
      {/* permission */}
      <div style={{ ...rowSB, ...secWrap }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Permission</div>
          <div style={{ fontSize: 12, color: permCfg.color, fontWeight: 600, marginTop: 2 }}>{permCfg.label}</div>
        </div>
        {perm !== 'granted' && (
          <button onClick={requestPerm} style={{ padding: '8px 14px', borderRadius: 10, background: 'var(--accent)', color: 'var(--on-accent)', border: 'none', font: 'inherit', fontSize: 12.5, fontWeight: 600, cursor: 'pointer' }}>
            {perm === 'denied' ? 'How to allow' : 'Allow notifications'}
          </button>
        )}
      </div>
      {perm === 'denied' && (
        <div style={{ fontSize: 11.5, color: 'var(--muted)', margin: '-2px 0 10px', lineHeight: 1.5 }}>
          Notifications are blocked for this site. Enable them in your browser’s site settings, then reload.
        </div>
      )}

      {/* Diary On This Day */}
      <div style={secWrap}>
        <div style={rowSB}>
          <div>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>📅 On This Day (Diary)</div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>Morning recap of past-year memories.</div>
          </div>
          <Toggle on={ns.diary.enabled} onClick={() => set('diary', 'enabled', !ns.diary.enabled)}/>
        </div>
        {ns.diary.enabled && (
          <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={rowSB}>
              <span style={{ fontSize: 12.5, color: 'var(--muted)' }}>Time</span>
              <input type="time" value={ns.diary.time} onChange={e => set('diary', 'time', e.target.value)} style={timeInput}/>
            </div>
            <label style={{ ...rowSB, cursor: 'pointer' }}>
              <span style={{ fontSize: 12.5, color: 'var(--muted)' }}>Notify even with no memories</span>
              <input type="checkbox" checked={ns.diary.sendEmpty} onChange={e => set('diary', 'sendEmpty', e.target.checked)}/>
            </label>
          </div>
        )}
      </div>

      {/* Goals reminder */}
      <div style={secWrap}>
        <div style={rowSB}>
          <div>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>🎯 Goals reminder</div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>Night nudge for unfinished goals.</div>
          </div>
          <Toggle on={ns.goals.enabled} onClick={() => set('goals', 'enabled', !ns.goals.enabled)}/>
        </div>
        {ns.goals.enabled && (
          <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={rowSB}>
              <span style={{ fontSize: 12.5, color: 'var(--muted)' }}>Time</span>
              <input type="time" value={ns.goals.time} onChange={e => set('goals', 'time', e.target.value)} style={timeInput}/>
            </div>
            <label style={{ ...rowSB, cursor: 'pointer' }}>
              <span style={{ fontSize: 12.5, color: 'var(--muted)' }}>Notify when all goals are done</span>
              <input type="checkbox" checked={ns.goals.sendDone} onChange={e => set('goals', 'sendDone', e.target.checked)}/>
            </label>
          </div>
        )}
      </div>

      <div style={{ fontSize: 11, color: 'var(--muted-2)', lineHeight: 1.5 }}>
        Reminders are checked while Nutri is open and fire once per day. Tap a reminder to jump to Diary or Goals.
      </div>
    </div>
  );
}

function Stat({ label, value }) {
  return (
    <div style={{
      background: 'var(--surface-2)', borderRadius: 10, padding: '10px 12px',
      border: '1px solid var(--border)',
    }}>
      <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{label}</div>
      <div style={{ fontSize: 20, fontWeight: 700, marginTop: 2 }}>{value}</div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════════
   QA DIAGNOSTICS PANEL — developer-only, collapsed by default.
   Uses window.NutriLogger (nutri-logger.jsx).
   ════════════════════════════════════════════════════════════════ */
function QAPanel({ card, h, sub, btnGhost }) {
  const [open, setOpen] = React.useState(false);
  const [logs, setLogs] = React.useState([]);
  const [healthResults, setHealthResults] = React.useState(null);
  const [validationResults, setValidationResults] = React.useState(null);
  const [healthRunning, setHealthRunning] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const [levelFilter, setLevelFilter] = React.useState('warning'); // 'info'|'warning'|'error'
  const logger = window.NutriLogger;

  function refresh() {
    if (!logger) return;
    setLogs(logger.getLogs({ level: levelFilter, limit: 100 }));
  }

  React.useEffect(() => { if (open) refresh(); }, [open, levelFilter]);

  async function runHealth() {
    if (!logger) return;
    setHealthRunning(true); setHealthResults(null);
    const results = await logger.runHealthCheck();
    setHealthResults(results);
    setHealthRunning(false);
    refresh();
  }

  function runValidation() {
    if (!logger) return;
    setValidationResults(logger.runProjectValidation());
    refresh();
  }

  function copyReport() {
    if (!logger) return;
    const report = logger.buildReport();
    if (navigator.clipboard) {
      navigator.clipboard.writeText(report).then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); });
    } else {
      // fallback for non-secure context
      const el = document.createElement('textarea'); el.value = report; el.style.position = 'fixed'; el.style.opacity = '0';
      document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el);
      setCopied(true); setTimeout(() => setCopied(false), 2000);
    }
  }

  function clearLogs() {
    if (!logger) return;
    if (!confirm('Clear all diagnostic logs? This only removes local log data, never your real app data.')) return;
    logger.clearLogs();
    setLogs([]); setHealthResults(null); setValidationResults(null);
  }

  const LEVEL_COLOR = { info: 'var(--muted)', warning: '#E89B3C', error: '#C2554E', critical: '#C2554E' };
  const STATUS_COLOR = { pass: '#4FA862', warn: '#E89B3C', fail: '#C2554E' };
  const STATUS_ICON  = { pass: '✓', warn: '⚠', fail: '✕' };

  const store = window.Store;
  const uid    = store && store.uid && store.uid();
  const movies = store && store.movies && store.movies().length;
  const lastSync = store && store.lastSyncAt && store.lastSyncAt();

  const smallBtn = {
    padding: '6px 10px', borderRadius: 8,
    background: 'var(--surface-2)', color: 'var(--text)',
    border: '1px solid var(--border-2)', font: 'inherit',
    fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
  };

  return (
    <div style={{ ...card, borderColor: 'rgba(87,132,216,0.3)', background: 'var(--surface)' }}>
      <button onClick={() => setOpen(v => !v)} style={{
        width: '100%', textAlign: 'left', background: 'none', border: 0,
        cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
      }}>
        <div>
          <h3 style={{ ...h, margin: 0, color: '#5784D8' }}>🔬 Diagnostics / QA Logs</h3>
          <p style={{ ...sub, margin: '3px 0 0', fontSize: 12 }}>Developer panel — error logs, health check, data validation.</p>
        </div>
        <span style={{ fontSize: 18, color: 'var(--muted)', flexShrink: 0 }}>{open ? '▾' : '▸'}</span>
      </button>

      {open && (
        <div style={{ marginTop: 14 }}>
          {/* Summary bar */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginBottom: 14 }}>
            {[
              { label: 'User', value: uid ? uid.slice(0,8)+'…' : '—' },
              { label: 'Movies', value: movies ?? '?' },
              { label: 'Last sync', value: lastSync ? new Date(lastSync).toLocaleTimeString() : '—' },
            ].map(s => (
              <div key={s.label} style={{ background: 'var(--surface-2)', borderRadius: 8, padding: '7px 9px', border: '1px solid var(--border)' }}>
                <div style={{ fontSize: 10, color: 'var(--muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.label}</div>
                <div style={{ fontSize: 13, fontWeight: 700, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{String(s.value)}</div>
              </div>
            ))}
          </div>

          {/* Action buttons */}
          <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap', marginBottom: 14 }}>
            <button onClick={runHealth} disabled={healthRunning} style={{ ...smallBtn, background: healthRunning ? 'var(--surface-3)' : 'var(--surface-2)' }}>
              {healthRunning ? '⏳ Checking…' : '⚡ Health Check'}
            </button>
            <button onClick={runValidation} style={smallBtn}>📋 Validate Data</button>
            <button onClick={copyReport} style={{ ...smallBtn, color: copied ? '#4FA862' : 'var(--text)' }}>
              {copied ? '✓ Copied!' : '📋 Copy report'}
            </button>
            <button onClick={clearLogs} style={{ ...smallBtn, color: '#C2554E' }}>🗑 Clear logs</button>
          </div>

          {/* Health check results */}
          {healthResults && (
            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 8 }}>Health Check</div>
              {healthResults.map((r, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '5px 0', borderBottom: '1px solid var(--border)' }}>
                  <span style={{ flexShrink: 0, fontWeight: 700, color: STATUS_COLOR[r.status] || 'var(--muted)', width: 16 }}>{STATUS_ICON[r.status] || '?'}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <span style={{ fontSize: 12.5, fontWeight: 600 }}>{r.name}</span>
                    {r.detail && <span style={{ fontSize: 11, color: 'var(--muted)', marginLeft: 6 }}>{r.detail}</span>}
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Data validation results */}
          {validationResults && (
            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 8 }}>Data Validation</div>
              {validationResults.length === 0
                ? <div style={{ fontSize: 12.5, color: '#4FA862' }}>✓ All projects look healthy</div>
                : validationResults.map((r, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '5px 0', borderBottom: '1px solid var(--border)' }}>
                    <span style={{ flexShrink: 0, fontWeight: 700, color: r.ok ? '#4FA862' : '#C2554E', width: 16 }}>{r.ok ? '✓' : '✕'}</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', marginRight: 4 }}>[{r.project}]</span>
                      <span style={{ fontSize: 12.5 }}>{r.msg}</span>
                    </div>
                  </div>
                ))}
            </div>
          )}

          {/* Log level filter */}
          <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
            {['info','warning','error'].map(l => (
              <button key={l} onClick={() => { setLevelFilter(l); }} style={{
                padding: '4px 9px', borderRadius: 999, font: 'inherit', fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
                background: levelFilter === l ? LEVEL_COLOR[l] : 'var(--surface-2)',
                color: levelFilter === l ? '#fff' : 'var(--muted)',
                border: '1px solid ' + (levelFilter === l ? LEVEL_COLOR[l] : 'var(--border-2)'),
              }}>{l}</button>
            ))}
            <button onClick={refresh} style={{ ...smallBtn, marginLeft: 'auto' }}>↻</button>
          </div>

          {/* Log list */}
          <div style={{ maxHeight: 320, overflowY: 'auto', fontFamily: 'monospace' }}>
            {logs.length === 0
              ? <div style={{ fontSize: 12, color: 'var(--muted)', padding: 8, textAlign: 'center' }}>No {levelFilter}+ logs</div>
              : logs.map((e, i) => (
                <div key={e.seq} style={{
                  padding: '6px 8px', borderRadius: 6, marginBottom: 4, fontSize: 11,
                  background: e.level === 'critical' || e.level === 'error' ? 'rgba(194,85,78,0.07)' : e.level === 'warning' ? 'rgba(232,155,60,0.07)' : 'var(--surface-2)',
                  borderLeft: '3px solid ' + (LEVEL_COLOR[e.level] || 'var(--border)'),
                }}>
                  <div style={{ display: 'flex', gap: 6, color: 'var(--muted-2)', marginBottom: 2, fontSize: 10 }}>
                    <span>{e.ts ? e.ts.slice(11, 19) : ''}</span>
                    <span style={{ color: LEVEL_COLOR[e.level], fontWeight: 700, textTransform: 'uppercase' }}>{e.level}</span>
                    <span>{e.module}</span>
                    <span>{e.action}</span>
                    {e._prevSession && <span style={{ color: 'var(--muted-2)' }}>(prev session)</span>}
                  </div>
                  <div style={{ color: 'var(--text)', fontSize: 11, wordBreak: 'break-word' }}>{e.message}</div>
                  {e.stack && (
                    <div style={{ marginTop: 4, color: 'var(--muted)', fontSize: 10, whiteSpace: 'pre-wrap', maxHeight: 60, overflowY: 'auto' }}>
                      {e.stack.split('\n').slice(0,3).join('\n')}
                    </div>
                  )}
                  {e.extra && Object.keys(e.extra).length > 0 && (
                    <div style={{ marginTop: 2, color: 'var(--muted-2)', fontSize: 10 }}>
                      {Object.entries(e.extra).map(([k,v]) => `${k}: ${v}`).join(' · ')}
                    </div>
                  )}
                </div>
              ))}
          </div>
          <div style={{ fontSize: 10.5, color: 'var(--muted-2)', marginTop: 10, lineHeight: 1.5 }}>
            Logs are stored locally only (max 500 in memory, 200 on disk). They never leave your device. Use "Copy report" to share with a developer.
          </div>
        </div>
      )}
    </div>
  );
}

window.SettingsScreen = SettingsScreen;
