// fc-settings.jsx, the settings detail screens the More tab links to but never
// had. Same "balanced" system + shared kit (CompactNav, GroupedList, Row, Toggle).
//   SettingsNotifications · per-type notification controls + quiet hours
//   SettingsAccount       · profile, units, linked sign-in, subscription, sign out
//   SettingsUnits         · kg ↔ lb with a live conversion preview
//   SettingsSubscription  · plan, renewal, change/cancel, restore, billing
//   SettingsData          · export data + delete account (destructive)
//   TransitionConfirm     · camp ↔ maintenance switch confirm (Logic §16.5)

const { Phone: GPhone, StatusBar: GStatusBar, HomeIndicator: GHome, CompactNav: GNav,
        GroupedList: GList, Row: GRow, Toggle: GToggle, SectionHeader: GSection,
        Eyebrow: GEyebrow, CoachTip: GCoachTip } = window;

const GB = '#a32a18';

// Caption under a grouped list (iOS footnote).
function ListNote({ children }) {
  return <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5, padding: '8px 6px 0', textWrap: 'pretty' }}>{children}</div>;
}
function Segmented({ options, value }) {
  const [sel, setSel] = React.useState(value);
  React.useEffect(() => setSel(value), [value]);
  return (
    <div style={{ display: 'flex', background: 'var(--paper-2)', borderRadius: 'var(--radius-ctl)', padding: 3, gap: 3, border: '1px solid var(--rule)' }}>
      {options.map((o) => {
        const on = o === sel;
        return <button key={o} type="button" onClick={(e) => { e.stopPropagation(); setSel(o); }} style={{ flex: 1, minHeight: 40, cursor: 'pointer', borderRadius: 'calc(var(--radius-ctl) - 3px)', background: on ? 'var(--paper)' : 'transparent', boxShadow: on ? 'var(--card-shadow)' : 'none', border: on ? 'var(--card-border)' : 'none', fontFamily: 'var(--sans)', fontSize: 14.5, fontWeight: on ? 600 : 500, color: on ? 'var(--ink)' : 'var(--ink-3)' }}>{o}</button>;
      })}
    </div>
  );
}
function DangerButton({ label }) {
  return <button style={{ width: '100%', minHeight: 52, borderRadius: 'var(--radius-ctl)', background: 'transparent', border: '1px solid color-mix(in srgb, var(--t-red) 40%, transparent)', color: 'var(--t-red)', fontFamily: 'var(--display)', fontSize: 13, letterSpacing: '0.12em', fontWeight: 600 }}>{label}</button>;
}

// ── NOTIFICATIONS ──────────────────────────────────────────────────────────────
function SettingsNotifications({ styleKey = 'balanced' }) {
  return (
    <GPhone styleKey={styleKey} label="Notifications">
      <GStatusBar />
      <GNav title="Notifications" trailing={<span style={{ width: 40 }} />} />
      <div style={{ flex: 1, padding: '6px 20px 28px', display: 'flex', flexDirection: 'column', gap: 22, overflowY: 'auto' }} className="scroll">
        <div>
          <GList>
            <GRow label="Allow notifications" chevron={false} control={<GToggle on={true} />} last />
          </GList>
          <ListNote>Master switch. Everything below only fires while this is on.</ListNote>
        </div>

        <div>
          <GSection>Daily</GSection>
          <GList>
            <GRow label="Morning weigh-in reminder" value="6:50 AM" />
            <GRow label="Nudge if I miss a log" chevron={false} control={<GToggle on={true} />} last />
          </GList>
          <ListNote>One consistent morning ping is the biggest driver of an accurate trend.</ListNote>
        </div>

        <div>
          <GSection>Camp</GSection>
          <GList>
            <GRow label="Fight-week alerts" chevron={false} control={<GToggle on={true} />} />
            <GRow label="Weigh-in day" chevron={false} control={<GToggle on={true} />} />
            <GRow label="Off-pace warnings" chevron={false} control={<GToggle on={true} />} last />
          </GList>
        </div>

        <div>
          <GSection>Progress & health</GSection>
          <GList>
            <GRow label="Weekly check-in" value="Sun 8 PM" />
            <GRow label="Cycle phase reminders" chevron={false} control={<GToggle on={true} />} note="Shown because cycle tracking is on. Flags phases where the scale runs high." />
            <GRow label="Learn · new articles" chevron={false} control={<GToggle on={false} />} last />
          </GList>
        </div>

        <div>
          <GSection>Quiet hours</GSection>
          <GList>
            <GRow label="Quiet hours" chevron={false} control={<GToggle on={true} />} />
            <GRow label="From" value="9:00 PM" />
            <GRow label="To" value="6:00 AM" last />
          </GList>
        </div>
      </div>
      <GHome />
    </GPhone>
  );
}

// ── ACCOUNT & UNITS ──────────────────────────────────────────────────────────────
function SettingsAccount({ styleKey = 'balanced' }) {
  return (
    <GPhone styleKey={styleKey} label="Account & units">
      <GStatusBar />
      <GNav title="Account" trailing={<span style={{ width: 40 }} />} />
      <div style={{ flex: 1, padding: '6px 20px 28px', display: 'flex', flexDirection: 'column', gap: 22, overflowY: 'auto' }} className="scroll">
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, background: 'var(--paper)', borderRadius: 'var(--radius)', boxShadow: 'var(--card-shadow)', border: 'var(--card-border)', padding: '18px 20px' }}>
          <div style={{ width: 48, height: 48, borderRadius: '50%', background: 'var(--ink)', color: 'var(--paper)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--display)', fontSize: 18, fontWeight: 600, flexShrink: 0 }}>AM</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>Alex Mercer</div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--ink-3)', marginTop: 2 }}>alex.mercer@gmail.com</div>
          </div>
        </div>

        <div>
          <GSection>Profile</GSection>
          <GList>
            <GRow label="Name" value="Alex Mercer" />
            <GRow label="Email" value="alex.mercer@…" />
            <GRow label="Password" value="Change" valueColor="var(--accent)" />
            <GRow label="Biological sex" value="Female" chevron={false} last />
          </GList>
        </div>

        <div>
          <GSection>Units</GSection>
          <div style={{ marginBottom: 12 }}><Segmented options={['Metric (kg)', 'Imperial (lb)']} value="Metric (kg)" /></div>
          <GList>
            <GRow label="Weight" value="Kilograms" />
            <GRow label="First day of week" value="Monday" chevron={false} last />
          </GList>
        </div>

        <div>
          <GSection>Subscription</GSection>
          <GList>
            <GRow label="Plan" value="Annual" chevron={false} />
            <GRow label="Manage subscription" chevron last />
          </GList>
        </div>

        <div>
          <GSection>Account</GSection>
          <GList>
            <GRow label="Privacy & data" chevron />
            <GRow label="Sign out" valueColor="var(--accent)" chevron={false} last />
          </GList>
        </div>
      </div>
      <GHome />
    </GPhone>
  );
}

// ── CHANGE UNITS ──────────────────────────────────────────────────────────────────
function SelRow({ label, sub, on, last, onClick }) {
  const body = (
    <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '0 18px', minHeight: sub ? 62 : 54 }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 16, fontWeight: on ? 600 : 400, color: 'var(--ink)' }}>{label}</div>
        {sub && <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>{sub}</div>}
      </div>
      <span style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, border: on ? 'none' : '1.6px solid var(--rule-2)', background: on ? GB : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {on && <svg width="11" height="9" viewBox="0 0 11 9" fill="none"><path d="M1 4.5 L4 7.5 L10 1" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>}
      </span>
    </div>
  );
  return (
    <div>
      {onClick
        ? <button type="button" onClick={onClick} style={{ display: 'block', width: '100%', textAlign: 'left', background: 'none', border: 'none', padding: 0, font: 'inherit', color: 'inherit', cursor: 'pointer' }}>{body}</button>
        : body}
      {!last && <div style={{ height: 1, background: 'var(--rule)', marginLeft: 18 }} />}
    </div>
  );
}
function SettingsUnits({ styleKey = 'balanced' }) {
  const [unit, setUnit] = React.useState('kg');
  return (
    <GPhone styleKey={styleKey} label="Units">
      <GStatusBar />
      <GNav title="Units" trailing={<button style={{ fontFamily: 'var(--sans)', fontSize: 15, color: 'var(--accent)', fontWeight: 600, minHeight: 44 }}>Done</button>} />
      <div style={{ flex: 1, padding: '6px 20px 28px', display: 'flex', flexDirection: 'column', gap: 22 }}>
        <div>
          <GSection>Weight</GSection>
          <GList>
            <SelRow label="Kilograms" sub="kg · 0.1 steps" on={unit === 'kg'} onClick={() => setUnit('kg')} />
            <SelRow label="Pounds" sub="lb · 0.2 steps" on={unit === 'lb'} onClick={() => setUnit('lb')} last />
          </GList>
        </div>

        {/* live conversion preview so the change is concrete before it lands */}
        <div style={{ background: 'var(--paper)', borderRadius: 'var(--radius)', boxShadow: 'var(--card-shadow)', border: 'var(--card-border)', padding: '20px' }}>
          <GEyebrow color="var(--accent)">Preview</GEyebrow>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 16 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>Limit</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 8 }}>
                <span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 34, color: 'var(--ink)' }}>74.4</span>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)', fontWeight: 600 }}>KG</span>
              </div>
            </div>
            <svg width="22" height="14" viewBox="0 0 24 16" fill="none" style={{ flexShrink: 0 }}><path d="M2 8 H21 M16 3 L21 8 L16 13" stroke="var(--rule-2)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>In pounds</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 8 }}>
                <span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 34, color: 'var(--accent)' }}>164.0</span>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)', fontWeight: 600 }}>LB</span>
              </div>
            </div>
          </div>
        </div>
        <ListNote>All your history, targets and division limits convert automatically. Your logged data never changes — only how it’s shown.</ListNote>
      </div>
      <GHome />
    </GPhone>
  );
}

// ── SUBSCRIPTION ──────────────────────────────────────────────────────────────────
function SettingsSubscription({ styleKey = 'balanced' }) {
  return (
    <GPhone styleKey={styleKey} label="Subscription">
      <GStatusBar />
      <GNav title="Subscription" trailing={<span style={{ width: 40 }} />} />
      <div style={{ flex: 1, padding: '6px 20px 28px', display: 'flex', flexDirection: 'column', gap: 22, overflowY: 'auto' }} className="scroll">
        {/* current plan hero */}
        <div style={{ background: 'var(--ink)', color: 'var(--paper)', borderRadius: 'var(--radius)', padding: '22px', position: 'relative', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontFamily: 'var(--display)', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(246,244,239,0.6)', fontWeight: 600 }}>Current plan</span>
            <span style={{ fontFamily: 'var(--display)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--paper)', border: '1px solid rgba(246,244,239,0.4)', borderRadius: 100, padding: '3px 10px' }}>Active</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 16 }}>
            <span style={{ fontFamily: 'var(--sans)', fontSize: 24, fontWeight: 700 }}>OnWeight Annual</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 5, marginTop: 8 }}>
            <span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 30 }}>$59</span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'rgba(246,244,239,0.7)', fontWeight: 600 }}>/ YEAR</span>
          </div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'rgba(246,244,239,0.8)', marginTop: 14 }}>Renews 14 Sep 2026 · $59/yr</div>
        </div>

        <div>
          <GSection>Manage</GSection>
          <GList>
            <GRow label="Switch to monthly" value="$8 / mo" />
            <GRow label="Payment method" value="•• 4242" />
            <GRow label="Billing history" chevron />
            <GRow label="Restore purchases" valueColor="var(--accent)" chevron={false} last />
          </GList>
          <ListNote>Manage or cancel anytime. Cancelling keeps full access until 14 Sep 2026, then drops to read-only history.</ListNote>
        </div>

        <DangerButton label="CANCEL SUBSCRIPTION" />
      </div>
      <GHome />
    </GPhone>
  );
}

// ── DATA & ACCOUNT (export / delete) ───────────────────────────────────────────
function SettingsData({ styleKey = 'balanced' }) {
  return (
    <GPhone styleKey={styleKey} label="Privacy & data">
      <GStatusBar />
      <GNav title="Privacy & data" trailing={<span style={{ width: 40 }} />} />
      <div style={{ flex: 1, padding: '6px 20px 28px', display: 'flex', flexDirection: 'column', gap: 22, overflowY: 'auto' }} className="scroll">
        <div>
          <GSection>Your data</GSection>
          <GList>
            <GRow label="Export my data" value="CSV" note="Every weigh-in, camp and result, emailed to you as a spreadsheet." />
            <GRow label="Download account info" chevron last />
          </GList>
        </div>

        <div>
          <GSection>Privacy</GSection>
          <GList>
            <GRow label="Share anonymous research data" chevron={false} control={<GToggle on={true} />} note="Helps improve the cut-science models. Never sold, never tied to your name." />
            <GRow label="Privacy policy" chevron last />
          </GList>
        </div>

        {/* destructive zone */}
        <div style={{ marginTop: 4 }}>
          <GSection>Danger zone</GSection>
          <div style={{ background: 'var(--t-red-soft)', border: '1px solid color-mix(in srgb, var(--t-red) 26%, transparent)', borderRadius: 'var(--radius)', padding: '18px 19px' }}>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 16, fontWeight: 700, color: 'var(--ink)' }}>Delete account</div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 13, lineHeight: 1.55, color: 'var(--ink-2)', marginTop: 8, textWrap: 'pretty' }}>Permanently erases your camps, history and plan. This can’t be undone — export your data first if you want to keep it.</div>
            <div style={{ marginTop: 16 }}><DangerButton label="DELETE ACCOUNT" /></div>
          </div>
        </div>
      </div>
      <GHome />
    </GPhone>
  );
}

// ── CAMP ↔ MAINTENANCE TRANSITION CONFIRM (Logic §16.5) ────────────────────────
// Shown when the athlete books a fight from maintenance, or ends a camp back to
// maintenance. Spells out exactly what changes so the switch is never a surprise.
function TransitionConfirm({ styleKey = 'balanced', dir = 'toCamp' }) {
  const toCamp = dir === 'toCamp';
  const title = toCamp ? 'Start a fight camp?' : 'End camp, back to maintenance?';
  const body = toCamp
    ? 'You’ve booked Sat 11 Jan. We’ll turn maintenance into a dated cut and rebuild your daily targets around weigh-in.'
    : 'Your fight’s done. We’ll archive this camp and switch you to a calmer maintenance routine until the next one.';
  const changes = toCamp
    ? [
        ['Weigh-ins', 'Weekly', 'Daily, fasted'],
        ['Targets', 'Maintenance band', 'Day-by-day cut'],
        ['Reminders', 'Light', 'Full camp set'],
      ]
    : [
        ['Weigh-ins', 'Daily, fasted', 'Weekly'],
        ['Targets', 'Day-by-day cut', 'Maintenance band'],
        ['Reminders', 'Full camp set', 'Light'],
      ];
  return (
    <GPhone styleKey={styleKey} label={toCamp ? 'Start camp?' : 'End camp?'}>
      <GStatusBar />
      <div style={{ height: 50, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: '0 16px', flexShrink: 0 }}>
        <button aria-label="Close" style={{ width: 38, height: 38, borderRadius: '50%', background: 'var(--paper-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M1 1 L13 13 M13 1 L1 13" stroke="var(--ink-2)" strokeWidth="1.6" strokeLinecap="round"/></svg>
        </button>
      </div>
      <div style={{ flex: 1, padding: '4px 24px 24px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ width: 64, height: 64, borderRadius: 18, background: toCamp ? 'var(--accent-soft)' : 'rgba(21,20,15,0.05)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: toCamp ? 'var(--accent)' : 'var(--ink-2)' }}>
          {toCamp
            ? <svg width="30" height="30" viewBox="0 0 32 32" fill="none"><rect x="5" y="7" width="22" height="20" rx="3" stroke="currentColor" strokeWidth="1.8"/><path d="M5 12 H27 M11 4 V8 M21 4 V8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><circle cx="21" cy="20" r="3.2" fill="currentColor"/></svg>
            : <svg width="30" height="30" viewBox="0 0 32 32" fill="none"><circle cx="16" cy="16" r="12" stroke="currentColor" strokeWidth="1.8"/><path d="M10 16 L14.5 20.5 L23 11" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>}
        </div>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 25, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.12, color: 'var(--ink)', marginTop: 20, textWrap: 'balance' }}>{title}</div>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 15, lineHeight: 1.55, color: 'var(--ink-2)', marginTop: 11, textWrap: 'pretty' }}>{body}</div>

        {/* what changes — before → after table */}
        <div style={{ background: 'var(--paper)', borderRadius: 'var(--radius)', boxShadow: 'var(--card-shadow)', border: 'var(--card-border)', padding: '6px 18px', marginTop: 22 }}>
          {changes.map((c, i) => (
            <div key={c[0]} style={{ display: 'flex', alignItems: 'center', gap: 10, minHeight: 52, borderTop: i ? '1px solid var(--rule)' : 'none' }}>
              <span style={{ flex: 1, fontFamily: 'var(--sans)', fontSize: 14.5, fontWeight: 500, color: 'var(--ink)' }}>{c[0]}</span>
              <span style={{ fontFamily: 'var(--sans)', fontSize: 13.5, color: 'var(--ink-3)' }}>{c[1]}</span>
              <svg width="16" height="11" viewBox="0 0 18 12" fill="none" style={{ flexShrink: 0 }}><path d="M1 6 H16 M12 2 L16 6 L12 10" stroke="var(--rule-2)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
              <span style={{ fontFamily: 'var(--sans)', fontSize: 13.5, fontWeight: 600, color: toCamp ? 'var(--accent)' : 'var(--ink)' }}>{c[2]}</span>
            </div>
          ))}
        </div>

        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
          <button style={{ width: '100%', minHeight: 54, borderRadius: 'var(--radius-ctl)', background: 'var(--ink)', color: 'var(--paper)', border: 'none', fontFamily: 'var(--display)', fontSize: 14, letterSpacing: '0.13em', fontWeight: 600 }}>{toCamp ? 'START CAMP' : 'END CAMP'}</button>
          <button style={{ width: '100%', minHeight: 50, borderRadius: 'var(--radius-ctl)', background: 'transparent', color: 'var(--ink-2)', border: 'none', fontFamily: 'var(--sans)', fontSize: 15, fontWeight: 500 }}>Not now</button>
        </div>
      </div>
      <GHome />
    </GPhone>
  );
}

Object.assign(window, { SettingsNotifications, SettingsAccount, SettingsUnits, SettingsSubscription, SettingsData, TransitionConfirm });
