// Settings page — theme, account, sidebar behaviour, integrations

const { useState: stUseState, useEffect: stUseEffect } = React;

const NOTE_PREFS_KEY = 'lynxe-note-prefs';

function loadNotePrefs() {
  try { return JSON.parse(localStorage.getItem(NOTE_PREFS_KEY) || '{}'); } catch { return {}; }
}

function saveNotePrefs(prefs) {
  try { localStorage.setItem(NOTE_PREFS_KEY, JSON.stringify(prefs)); } catch {}
}

function Settings({ theme, onThemeChange, sidebarCollapsed, onSidebarCollapseChange, onNav }) {
  // Notes & Recording
  const [autoTitle, setAutoTitle] = stUseState(true);
  const [recSound, setRecSound] = stUseState(false);
  const [autoSummarise, setAutoSummarise] = stUseState(true);
  const [transcribeOffline, setTranscribeOffline] = stUseState(false);

  // Note preferences (persisted to localStorage)
  const [noteDetail, setNoteDetail] = stUseState('balanced');
  const [noteFormat, setNoteFormat] = stUseState('traditional');
  const [notePersonal, setNotePersonal] = stUseState('');

  stUseEffect(() => {
    const p = loadNotePrefs();
    if (p.detail)   setNoteDetail(p.detail);
    if (p.format)   setNoteFormat(p.format);
    if (p.personal !== undefined) setNotePersonal(p.personal);
  }, []);

  function updateNotePrefs(patch) {
    const current = loadNotePrefs();
    saveNotePrefs({ ...current, ...patch });
  }

  // Notifications
  const [dailyReminders, setDailyReminders] = stUseState(true);
  const [deadlineAlerts, setDeadlineAlerts] = stUseState(true);
  const [classroomPing, setClassroomPing] = stUseState(true);
  const [weeklyDigest, setWeeklyDigest] = stUseState(false);

  // Integrations
  const [notionConnected, setNotionConnected] = stUseState(true);
  const [classroomConnected, setClassroomConnected] = stUseState(true);
  const [calendarSync, setCalendarSync] = stUseState(false);

  // Appearance
  const [showSubjectColors, setShowSubjectColors] = stUseState(true);
  const [reducedMotion, setReducedMotion] = stUseState(false);

  // Privacy
  const [shareUsage, setShareUsage] = stUseState(false);

  return (
    <>
      <Topbar crumbs={['Settings']} />
      <div className="content">
        <div className="settings-page">
          <div style={{ marginBottom: 28 }}>
            <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.018em' }}>Settings</div>
            <div className="dim" style={{ fontSize: 12.5, marginTop: 2 }}>Manage your account, appearance, and preferences.</div>
          </div>

          <Section title="Account">
            <Row title="Sahishnu Y." help="sahishnu@lynxe.app">
              <button className="btn" onClick={() => onNav('account')}>Manage</button>
            </Row>
            <Row title="School" help="Riverside High · Year 12">
              <button className="btn ghost" onClick={() => onNav('account')}>Change</button>
            </Row>
          </Section>

          <Section title="Appearance">
            <Row title="Theme" help="Match your system, or pick one.">
              <div className="theme-swatches" style={{ marginRight: 0 }}>
                <ThemePreview kind="light" selected={theme === 'light'} onClick={() => onThemeChange('light')} />
                <ThemePreview kind="dark"  selected={theme === 'dark'}  onClick={() => onThemeChange('dark')}  />
                <ThemePreview kind="system" selected={theme === 'system'} onClick={() => onThemeChange('system')} />
              </div>
            </Row>
            <Row title="Show subject colour dots" help="Tiny colour dots next to subject names. Off for a fully neutral interface.">
              <Toggle on={showSubjectColors} onChange={setShowSubjectColors} />
            </Row>
            <Row title="Collapsed sidebar" help="Show only icons in the left navigation.">
              <Toggle on={sidebarCollapsed} onChange={onSidebarCollapseChange} />
            </Row>
            <Row title="Reduce motion" help="Disable non-essential animations and transitions.">
              <Toggle on={reducedMotion} onChange={setReducedMotion} />
            </Row>
          </Section>

          <Section title="Notes & Recording">
            <Row title="Auto-title lectures" help="Suggest a title based on subject and date.">
              <Toggle on={autoTitle} onChange={setAutoTitle} />
            </Row>
            <Row title="Auto-summarise after recording" help="Generate a structured summary as soon as a lecture ends.">
              <Toggle on={autoSummarise} onChange={setAutoSummarise} />
            </Row>
            <Row title="Recording sound effect" help="Play a soft chime when a recording starts and stops.">
              <Toggle on={recSound} onChange={setRecSound} />
            </Row>
            <Row title="Offline transcription" help="Transcribe on-device when you're not connected. Slower, more private.">
              <Toggle on={transcribeOffline} onChange={setTranscribeOffline} />
            </Row>
          </Section>

          <Section title="Note Preferences">
            <Row title="Detail level" help="How much depth should your notes go into?">
              <SegmentedControl
                value={noteDetail}
                options={[
                  { value: 'concise',       label: 'Concise' },
                  { value: 'balanced',      label: 'Balanced' },
                  { value: 'comprehensive', label: 'Detailed' },
                ]}
                onChange={v => { setNoteDetail(v); updateNotePrefs({ detail: v }); }}
              />
            </Row>
            <Row title="Format" help="How should your notes be laid out?">
              <SegmentedControl
                value={noteFormat}
                options={[
                  { value: 'traditional', label: 'Headers & bullets' },
                  { value: 'cornell',     label: 'Cornell method' },
                  { value: 'prose',       label: 'Flowing prose' },
                ]}
                onChange={v => { setNoteFormat(v); updateNotePrefs({ format: v }); }}
              />
            </Row>
            <Row title="Your learning style" help="Tell Lynxe how you learn best. This shapes every note it writes for you.">
              <div />
            </Row>
            <textarea
              className="textarea"
              style={{ marginTop: -8, marginBottom: 4 }}
              rows={3}
              placeholder={`e.g. "I'm a visual learner — use analogies and worked examples. I struggle with abstract notation."`}
              value={notePersonal}
              onChange={e => { setNotePersonal(e.target.value); updateNotePrefs({ personal: e.target.value }); }}
            />
          </Section>

          <Section title="Notifications">
            <Row title="Daily reminders" help="A gentle nudge each morning with the day's plan.">
              <Toggle on={dailyReminders} onChange={setDailyReminders} />
            </Row>
            <Row title="Deadline alerts" help="Notify me 7, 3, and 1 day before a mission is due.">
              <Toggle on={deadlineAlerts} onChange={setDeadlineAlerts} />
            </Row>
            <Row title="New classroom posts" help="Ping me when a teacher posts an announcement or assignment.">
              <Toggle on={classroomPing} onChange={setClassroomPing} />
            </Row>
            <Row title="Weekly digest email" help="A Sunday recap of progress, missions, and what's coming up.">
              <Toggle on={weeklyDigest} onChange={setWeeklyDigest} />
            </Row>
          </Section>

          <Section title="Integrations">
            <Row title="Notion" help={notionConnected ? 'Connected · all notes live in your Notion workspace.' : 'Disconnected · notes will be stored in Lynxe only.'}>
              <Toggle on={notionConnected} onChange={setNotionConnected} />
            </Row>
            <Row title="Google Classroom" help={classroomConnected ? 'Synced 4 minutes ago.' : 'Disconnected · classroom posts will not appear.'}>
              <div className="hstack" style={{ gap: 8 }}>
                {classroomConnected && (
                  <button className="btn ghost" onClick={() => alert('Re-syncing Google Classroom…')}>Re-sync</button>
                )}
                <Toggle on={classroomConnected} onChange={setClassroomConnected} />
              </div>
            </Row>
            <Row title="Calendar sync" help="Mirror missions and lectures into your Google or Apple calendar.">
              <Toggle on={calendarSync} onChange={setCalendarSync} />
            </Row>
          </Section>

          <Section title="Privacy">
            <Row title="Share anonymous usage data" help="Help improve Lynxe by sharing aggregated, anonymous interaction data.">
              <Toggle on={shareUsage} onChange={setShareUsage} />
            </Row>
          </Section>

          <Section title="Danger zone">
            <Row title="Replay onboarding" help="Walk through the welcome flow again. Won't delete your data.">
              <button className="btn" onClick={() => {
                try { localStorage.removeItem('lynxe-profile'); } catch {}
                location.reload();
              }}>Replay</button>
            </Row>
            <Row title="Sign out" help="You'll need to sign in again on this device.">
              <button className="btn" onClick={() => {
                if (confirm('Sign out of Lynxe?')) {
                  try { localStorage.removeItem('lynxe-authed'); } catch {}
                  location.reload();
                }
              }}>Sign out</button>
            </Row>
          </Section>

          <div className="dim" style={{ fontSize: 11, marginTop: 36, textAlign: 'center' }}>
            Lynxe · v0.4.0 · build 240429
          </div>
        </div>
      </div>
    </>
  );
}

function Section({ title, children }) {
  return (
    <div className="settings-section">
      <div className="settings-section-title">{title}</div>
      <div>{children}</div>
    </div>
  );
}

function Row({ title, help, children }) {
  return (
    <div className="settings-row">
      <div>
        <div className="row-title">{title}</div>
        {help && <div className="row-help">{help}</div>}
      </div>
      <div>{children}</div>
    </div>
  );
}

function ThemePreview({ kind, selected, onClick }) {
  let barBg, contentBg, lineBg;
  if (kind === 'light') {
    barBg = '#fafafa'; contentBg = '#ffffff'; lineBg = '#d4d4d8';
  } else if (kind === 'dark') {
    barBg = '#0d0d0f'; contentBg = '#0a0a0c'; lineBg = '#2c2c33';
  } else {
    barBg = 'linear-gradient(90deg, #fafafa 50%, #0d0d0f 50%)';
    contentBg = 'linear-gradient(90deg, #ffffff 50%, #0a0a0c 50%)';
    lineBg = '#888';
  }
  const label = kind === 'system' ? 'Auto' : (kind === 'light' ? 'Light' : 'Dark');
  return (
    <div style={{ position: 'relative', paddingBottom: 18 }}>
      <div className={`theme-swatch ${selected ? 'selected' : ''}`} onClick={onClick}>
        <div className="ts-bar" style={{ background: barBg }} />
        <div className="ts-content" style={{ background: contentBg }}>
          <div className="ts-line" style={{ background: lineBg }} />
          <div className="ts-line" style={{ background: lineBg }} />
          <div className="ts-line" style={{ background: lineBg }} />
        </div>
      </div>
      <div className="ts-label" style={{ color: selected ? 'var(--fg)' : 'var(--fg-3)', fontWeight: selected ? 500 : 400 }}>{label}</div>
    </div>
  );
}

function SegmentedControl({ value, options, onChange }) {
  return (
    <div className="hstack" style={{ gap: 2, background: 'var(--bg)', border: '1px solid var(--border-2)', borderRadius: 'var(--r-2)', padding: 2 }}>
      {options.map(o => (
        <button
          key={o.value}
          onClick={() => onChange(o.value)}
          style={{
            fontSize: 11.5, padding: '4px 10px', borderRadius: 4, border: 'none', cursor: 'pointer',
            background: value === o.value ? 'var(--bg-elev)' : 'transparent',
            color: value === o.value ? 'var(--fg)' : 'var(--fg-3)',
            fontWeight: value === o.value ? 500 : 400,
            boxShadow: value === o.value ? 'var(--shadow-sm)' : 'none',
          }}
        >{o.label}</button>
      ))}
    </div>
  );
}

window.Settings = Settings;
window.loadNotePrefs = loadNotePrefs;
