// settings.jsx — functional settings sheets + data export/import

// ── Shared bottom-sheet shell ────────────────────────────────
function SheetShell({ title, onClose, children, subtitle }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 45, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)', animation: 'psyfade .2s ease' }} />
      <div style={{ position: 'relative', background: 'var(--surface)', borderTopLeftRadius: 28, borderTopRightRadius: 28,
        borderTop: '1px solid var(--border)', padding: '14px 20px 34px', maxHeight: '88%', overflowY: 'auto',
        animation: 'psyslide .28s cubic-bezier(.2,.8,.2,1)' }}>
        <div style={{ width: 40, height: 5, borderRadius: 999, background: 'var(--surface-3)', margin: '0 auto 16px' }} />
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <Display size={26}>{title}</Display>
            {subtitle && <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>{subtitle}</div>}
          </div>
          <button onClick={onClose} style={{ background: 'var(--surface-2)', border: 'none', borderRadius: 999, width: 34, height: 34, color: 'var(--text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="close" size={18} /></button>
        </div>
        {children}
      </div>
    </div>
  );
}

// ── Small controls ───────────────────────────────────────────
function Seg({ options, value, onChange }) {
  const c = useTheme();
  return (
    <div style={{ display: 'flex', gap: 6, background: 'var(--surface-2)', borderRadius: 'var(--radius-sm)', padding: 4 }}>
      {options.map(o => {
        const v = typeof o === 'object' ? o.value : o;
        const l = typeof o === 'object' ? o.label : o;
        const on = v === value;
        return (
          <button key={v} onClick={() => onChange(v)} style={{ flex: 1, padding: '11px 8px', borderRadius: 'calc(var(--radius-sm) - 3px)', cursor: 'pointer', border: 'none',
            background: on ? c.accent : 'transparent', color: on ? c.accentInk : 'var(--muted)',
            fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700, transition: 'all .15s' }}>{l}</button>
        );
      })}
    </div>
  );
}

function RowToggle({ label, sub, value, onChange }) {
  const c = useTheme();
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15, color: 'var(--text)' }}>{label}</div>
        {sub && <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--muted)', marginTop: 2 }}>{sub}</div>}
      </div>
      <button onClick={() => onChange(!value)} style={{ position: 'relative', width: 50, height: 30, borderRadius: 999, border: 'none', cursor: 'pointer', flexShrink: 0,
        background: value ? c.accent : 'var(--surface-3)', transition: 'background .18s' }}>
        <span style={{ position: 'absolute', top: 3, left: 3, width: 24, height: 24, borderRadius: 999, background: '#fff',
          transform: value ? 'translateX(20px)' : 'none', transition: 'transform .18s', boxShadow: '0 1px 3px rgba(0,0,0,.3)' }} />
      </button>
    </div>
  );
}

function FieldLabel({ children }) {
  return <Eyebrow style={{ marginBottom: 9 }}>{children}</Eyebrow>;
}

// ── Export / import ──────────────────────────────────────────
function downloadBackup(payload) {
  const data = { app: 'PsyFit', version: 1, exportedAt: new Date().toISOString(), ...payload };
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'psyfit-backup-' + new Date().toISOString().slice(0, 10) + '.json';
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1500);
}

// ── Settings sheet ───────────────────────────────────────────
function SettingsSheet({ kind, onClose, ctx }) {
  const c = useTheme();
  const { settings, setSettings, theme, setPref, getExport, onImport } = ctx;
  const [importMsg, setImportMsg] = React.useState(null);
  const [confirmClear, setConfirmClear] = React.useState(false);
  const fileRef = React.useRef(null);

  // UNITS ──────────────────────────────────────────────────
  if (kind === 'units') {
    return (
      <SheetShell title="Units" subtitle="How weights are shown and entered." onClose={onClose}>
        <FieldLabel>Weight unit</FieldLabel>
        <Seg options={[{ value: 'lb', label: 'Pounds (lb)' }, { value: 'kg', label: 'Kilograms (kg)' }]}
          value={settings.unit} onChange={(v) => setSettings({ unit: v })} />
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--muted)', marginTop: 12 }}>
          Existing data is stored once and converted on the fly — switching units never changes your logged numbers.
        </div>
      </SheetShell>
    );
  }

  // REMINDERS ──────────────────────────────────────────────
  if (kind === 'reminders') {
    const reqPermission = async () => {
      if (!('Notification' in window)) { setImportMsg('Notifications are not supported on this device.'); return; }
      const res = await Notification.requestPermission();
      setImportMsg(res === 'granted' ? 'Notifications enabled.' : 'Permission denied — enable it in your browser settings.');
    };
    const testNote = () => {
      if (('Notification' in window) && Notification.permission === 'granted') {
        try { new Notification('PsyFit', { body: "This is your daily nudge. Let's train 🔥", icon: 'icons/icon-192.png' }); } catch (e) {}
      } else { reqPermission(); }
    };
    return (
      <SheetShell title="Reminders" subtitle="A daily nudge to keep your streak alive." onClose={onClose}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <RowToggle label="Daily reminder" sub="Get a notification to train" value={settings.reminderOn}
            onChange={(v) => { setSettings({ reminderOn: v }); if (v) reqPermission(); }} />
          <div style={{ opacity: settings.reminderOn ? 1 : 0.4, pointerEvents: settings.reminderOn ? 'auto' : 'none' }}>
            <FieldLabel>Time</FieldLabel>
            <input type="time" value={settings.reminderTime} onChange={(e) => setSettings({ reminderTime: e.target.value })}
              style={{ width: '100%', boxSizing: 'border-box', height: 48, padding: '0 16px', borderRadius: 'var(--radius-sm)',
                background: 'var(--surface-2)', border: '1px solid var(--border)', color: 'var(--text)', fontFamily: 'var(--font-body)', fontSize: 16, outline: 'none', colorScheme: c.dark ? 'dark' : 'light' }} />
          </div>
          {importMsg && <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--muted)' }}>{importMsg}</div>}
          <button onClick={testNote} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '13px', borderRadius: 'var(--radius-sm)',
            background: 'var(--surface-2)', border: '1px solid var(--border)', color: 'var(--text)', cursor: 'pointer', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14 }}>
            <Icon name="bell" size={17} /> Send a test reminder
          </button>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--dim)', lineHeight: 1.4 }}>
            Reminders fire while PsyFit is installed and running in the background. For guaranteed delivery when fully closed, a push service is needed.
          </div>
        </div>
      </SheetShell>
    );
  }

  // WEEKLY GOAL ────────────────────────────────────────────
  if (kind === 'goal') {
    const g = settings.weeklyGoal;
    return (
      <SheetShell title="Weekly Goal" subtitle="Workouts you aim to complete each week." onClose={onClose}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, padding: '6px 0 14px' }}>
          <button onClick={() => setSettings({ weeklyGoal: Math.max(1, g - 1) })} style={{ width: 52, height: 52, borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)', background: 'var(--surface-2)', color: 'var(--text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="minus" size={22} /></button>
          <div style={{ textAlign: 'center', minWidth: 90 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 64, color: c.accent, lineHeight: 0.85 }}>{g}</div>
            <Eyebrow style={{ marginTop: 6 }}>per week</Eyebrow>
          </div>
          <button onClick={() => setSettings({ weeklyGoal: Math.min(7, g + 1) })} style={{ width: 52, height: 52, borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)', background: 'var(--surface-2)', color: 'var(--text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="plus" size={22} /></button>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          {[3, 4, 5, 6].map(n => (
            <button key={n} onClick={() => setSettings({ weeklyGoal: n })} style={{ flex: 1, padding: '10px 0', borderRadius: 'var(--radius-sm)', cursor: 'pointer',
              border: '1px solid var(--border)', background: g === n ? 'var(--surface-3)' : 'transparent',
              fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700, color: g === n ? 'var(--text)' : 'var(--muted)' }}>{n}×</button>
          ))}
        </div>
      </SheetShell>
    );
  }

  // PREFERENCES ────────────────────────────────────────────
  if (kind === 'preferences') {
    return (
      <SheetShell title="Preferences" subtitle="Make PsyFit yours." onClose={onClose}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div>
            <FieldLabel>Color scheme</FieldLabel>
            <div style={{ display: 'flex', gap: 10 }}>
              {ACCENTS.map(a => {
                const on = a.c.toLowerCase() === String(theme.accent).toLowerCase();
                return (
                  <button key={a.c} onClick={() => setPref('accent', a.c)} style={{ flex: 1, height: 52, borderRadius: 'var(--radius-sm)', cursor: 'pointer', position: 'relative',
                    background: a.c, border: on ? '3px solid var(--text)' : '1px solid var(--border)' }}>
                    {on && <span style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: a.ink }}><Icon name="check" size={22} /></span>}
                  </button>
                );
              })}
            </div>
          </div>
          <div>
            <FieldLabel>Theme</FieldLabel>
            <Seg options={[{ value: true, label: 'Dark' }, { value: false, label: 'Light' }]} value={theme.dark} onChange={(v) => setPref('dark', v)} />
          </div>
          <div>
            <FieldLabel>Display font</FieldLabel>
            <Seg options={['Anton', 'Bebas', 'Oswald']} value={theme.font} onChange={(v) => setPref('font', v)} />
          </div>
          <div>
            <FieldLabel>Home layout</FieldLabel>
            <Seg options={['Hero', 'Stats', 'Editorial']} value={theme.homeLayout} onChange={(v) => setPref('homeLayout', v)} />
          </div>
          <RowToggle label="Show photos" sub="Hero images across the app" value={theme.imagery} onChange={(v) => setPref('imagery', v)} />
        </div>
      </SheetShell>
    );
  }

  // DATA / BACKUP ──────────────────────────────────────────
  if (kind === 'data') {
    const doImport = (e) => {
      const f = e.target.files && e.target.files[0];
      if (!f) return;
      const reader = new FileReader();
      reader.onload = () => {
        try {
          const data = JSON.parse(reader.result);
          if (!data || data.app !== 'PsyFit') { setImportMsg('That doesn\'t look like a PsyFit backup.'); return; }
          onImport(data);
          setImportMsg('Restored! Your data is back.');
        } catch (err) { setImportMsg('Could not read that file.'); }
      };
      reader.readAsText(f);
      e.target.value = '';
    };
    return (
      <SheetShell title="Backup & Export" subtitle="Keep your data safe — export it anytime." onClose={onClose}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <AccentButton onClick={() => downloadBackup(getExport())} icon={<Icon name="share" size={18} />}>Export my data</AccentButton>
          <button onClick={() => fileRef.current && fileRef.current.click()} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '15px', borderRadius: 'var(--radius-sm)',
            background: 'var(--surface-2)', border: '1px solid var(--border)', color: 'var(--text)', cursor: 'pointer', fontFamily: 'var(--font-display)', fontSize: 17, textTransform: 'uppercase', letterSpacing: 0.5 }}>
            <Icon name="plus" size={18} /> Import backup
          </button>
          <input ref={fileRef} type="file" accept="application/json,.json" onChange={doImport} style={{ display: 'none' }} />
          {importMsg && <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, color: c.accent, textAlign: 'center' }}>{importMsg}</div>}
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--dim)', lineHeight: 1.5, marginTop: 4 }}>
            Your export is a single file containing your workouts, exercises, profile, photos, and settings. Save it to your files or cloud drive. Import it on any device to restore everything.
          </div>

          {/* Danger zone */}
          <div style={{ height: 1, background: 'var(--border)', margin: '8px 0 4px' }} />
          <Eyebrow style={{ color: c.danger }}>Danger zone</Eyebrow>
          {!confirmClear ? (
            <button onClick={() => setConfirmClear(true)} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '15px', borderRadius: 'var(--radius-sm)',
              background: 'transparent', border: '1px solid ' + c.danger, color: c.danger, cursor: 'pointer', fontFamily: 'var(--font-display)', fontSize: 17, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              <Icon name="trash" size={18} /> Clear workout history
            </button>
          ) : (
            <div style={{ border: '1px solid ' + c.danger, borderRadius: 'var(--radius-sm)', padding: 16, display: 'flex', flexDirection: 'column', gap: 14,
              background: c.danger + '14' }}>
              <div style={{ display: 'flex', gap: 11 }}>
                <span style={{ color: c.danger, flexShrink: 0, marginTop: 1 }}><Icon name="trash" size={22} /></span>
                <div>
                  <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15, color: 'var(--text)' }}>Clear all workout history?</div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--muted)', marginTop: 3, lineHeight: 1.4 }}>
                    This wipes your logged sets, streak, stats, PRs and calendar history. Your exercises and plan stay. This can't be undone — export a backup first if you want to keep it.
                  </div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10 }}>
                <button onClick={() => setConfirmClear(false)} style={{ flex: 1, padding: '13px', borderRadius: 'var(--radius-sm)', cursor: 'pointer',
                  background: 'var(--surface-2)', border: '1px solid var(--border)', color: 'var(--text)', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14 }}>Cancel</button>
                <button onClick={() => { ctx.clearHistory(); onClose(); }} style={{ flex: 1, padding: '13px', borderRadius: 'var(--radius-sm)', cursor: 'pointer',
                  background: c.danger, border: 'none', color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14 }}>Yes, clear it</button>
              </div>
            </div>
          )}
        </div>
      </SheetShell>
    );
  }

  return null;
}

Object.assign(window, { SheetShell, SettingsSheet, downloadBackup });
