/* ===== Settings — fully functional, persisted via setProfile / tweaks ===== */

/* ---- Backup helpers: export/import ALL persisted app data ---- */
function exportAppData() {
  var payload = { app: 'sectionly', version: 2, exportedAt: new Date().toISOString(), data: window.Store.state() };
  var blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
  var url = URL.createObjectURL(blob);
  var a = document.createElement('a');
  a.href = url;
  a.download = 'sectionly-backup-' + new Date().toISOString().slice(0, 10) + '.json';
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
}
function importAppData(file, done) {
  var r = new FileReader();
  r.onload = function () {
    try {
      var parsed = JSON.parse(String(r.result));
      var data = parsed && parsed.data ? parsed.data : parsed;
      if (!data || typeof data !== 'object') { done(false, 0); return; }
      window.Store.replaceAll(data);
      var n = (data.userSections ? data.userSections.length : 0);
      done(true, n);
    } catch (e) { done(false, 0); }
  };
  r.readAsText(file);
}

function Switch({ on, onClick }) {
  return <button type="button" className={'switch' + (on ? ' on' : '')} onClick={onClick} aria-pressed={on} />;
}

function SettingsView({ nav, route, profile, setProfile, notify, t, setTweak, favs }) {
  const tabs = [
    { id: 'profile', label: 'Profile', icon: 'user' },
    { id: 'account', label: 'Account', icon: 'gear' },
    { id: 'appearance', label: 'Appearance', icon: 'palette' },
    { id: 'notifications', label: 'Notifications', icon: 'bell' },
    { id: 'billing', label: 'Billing & Plan', icon: 'card' },
    { id: 'security', label: 'Security', icon: 'shield' }
  ];
  const [tab, setTab] = useState(route.tab || 'profile');

  return (
    <div className="content-inner">
      <span className="eyebrow">Account</span>
      <h2 style={{ fontSize: 28, margin: '6px 0 4px', fontFamily: 'var(--font-display)' }}>Settings</h2>
      <p style={{ color: 'var(--text-2)', marginTop: 0, marginBottom: 26 }}>Manage your profile, preferences and workspace.</p>

      <div className="settings-layout">
        <nav className="settings-nav">
          {tabs.map(tb =>
            <button key={tb.id} className={tab === tb.id ? 'active' : ''} onClick={() => setTab(tb.id)}>
              <Icon name={tb.icon} size={18} /> {tb.label}
            </button>)}
          <div className="sn-sep" />
          <button className="danger-link" onClick={() => { setTab('security'); }}>
            <Icon name="logout" size={18} /> Sign out
          </button>
        </nav>

        <div className="set-panel">
          {tab === 'profile' && <ProfileTab profile={profile} setProfile={setProfile} notify={notify} />}
          {tab === 'account' && <AccountTab profile={profile} setProfile={setProfile} notify={notify} />}
          {tab === 'appearance' && <AppearanceTab t={t} setTweak={setTweak} notify={notify} />}
          {tab === 'notifications' && <NotificationsTab profile={profile} setProfile={setProfile} notify={notify} />}
          {tab === 'billing' && <BillingTab favs={favs} nav={nav} notify={notify} />}
          {tab === 'security' && <SecurityTab profile={profile} setProfile={setProfile} notify={notify} />}
        </div>
      </div>
    </div>
  );
}

/* ---------- Profile ---------- */
function ProfileTab({ profile, setProfile, notify }) {
  const [form, setForm] = useState(profile);
  const fileRef = useRef(null);
  const dirty = JSON.stringify(form) !== JSON.stringify(profile);
  const set = (k, v) => setForm(f => Object.assign({}, f, { [k]: v }));

  const onPick = (e) => {
    const file = e.target.files[0]; if (!file) return;
    if (!/^image\//.test(file.type)) { notify('Please choose an image', true); return; }
    const r = new FileReader();
    r.onload = () => set('avatar', String(r.result));
    r.readAsDataURL(file);
  };

  return (
    <>
      <div className="set-card">
        <h3>Profile photo</h3>
        <p className="sub">This appears in the sidebar and on your shared sections.</p>
        <div className="avatar-edit">
          <div className="avatar-lg">{form.avatar ? <img src={form.avatar} alt={form.name} /> : initials(form.name)}</div>
          <div className="ae-actions">
            <input ref={fileRef} type="file" accept="image/*" onChange={onPick} style={{ display: 'none' }} />
            <button className="btn btn-sm" onClick={() => fileRef.current.click()}><Icon name="camera" size={15} /> Upload new</button>
            {form.avatar && <button className="btn btn-sm btn-ghost" onClick={() => set('avatar', '')}>Remove</button>}
          </div>
        </div>
      </div>

      <div className="set-card">
        <h3>Personal information</h3>
        <p className="sub">Update your name and how others see you.</p>
        <div className="set-grid2" style={{ marginBottom: 16 }}>
          <div className="field"><label>Full name</label><input className="t-input" value={form.name} onChange={e => set('name', e.target.value)} /></div>
          <div className="field"><label>Role</label><input className="t-input" value={form.role} onChange={e => set('role', e.target.value)} /></div>
        </div>
        <div className="set-grid2" style={{ marginBottom: 16 }}>
          <div className="field"><label>Email</label><input className="t-input" type="email" value={form.email} onChange={e => set('email', e.target.value)} /></div>
          <div className="field"><label>Company</label><input className="t-input" value={form.company} onChange={e => set('company', e.target.value)} /></div>
        </div>
        <div className="field"><label>Bio</label><textarea className="t-input" style={{ fontFamily: 'inherit', fontSize: 14, minHeight: 84 }} value={form.bio} onChange={e => set('bio', e.target.value)} /></div>
      </div>

      <div className="set-foot">
        <button className="btn btn-primary" disabled={!dirty} style={!dirty ? { opacity: .5, cursor: 'not-allowed' } : {}}
          onClick={() => { setProfile(form); notify('Profile saved'); }}>
          <Icon name="save" size={16} /> Save changes
        </button>
        {dirty ? <button className="btn" onClick={() => setForm(profile)}>Discard</button>
          : <span className="set-saved"><Icon name="check" size={15} /> All changes saved</span>}
      </div>
    </>
  );
}

/* ---------- Account ---------- */
function AccountTab({ profile, setProfile, notify }) {
  const [lang, setLang] = useState(profile.lang || 'English (US)');
  const [tz, setTz] = useState(profile.tz || '(GMT+6) Dhaka');
  const importRef = useRef(null);
  const customCount = window.SectionStore.list().length;
  const editedCount = window.SectionStore.modifiedCount();
  const backupSummary = customCount + ' custom section' + (customCount === 1 ? '' : 's')
    + (editedCount ? ' \u00b7 ' + editedCount + ' edited built-in' + (editedCount === 1 ? '' : 's') : '')
    + ' \u00b7 favorites, profile & preferences';
  return (
    <>
      <div className="set-card">
        <h3>Regional</h3>
        <p className="sub">Set your language and timezone.</p>
        <div className="set-grid2">
          <div className="field"><label>Language</label>
            <div className="select-wrap">
              <select className="t-input" value={lang} onChange={e => setLang(e.target.value)}>
                {['English (US)', 'English (UK)', 'বাংলা', 'Deutsch', 'Español', 'Français', '日本語'].map(l => <option key={l}>{l}</option>)}
              </select><span className="select-chev"><Icon name="arrow" size={16} /></span>
            </div>
          </div>
          <div className="field"><label>Timezone</label>
            <div className="select-wrap">
              <select className="t-input" value={tz} onChange={e => setTz(e.target.value)}>
                {['(GMT+6) Dhaka', '(GMT+0) London', '(GMT-5) New York', '(GMT-8) Los Angeles', '(GMT+1) Berlin', '(GMT+9) Tokyo'].map(z => <option key={z}>{z}</option>)}
              </select><span className="select-chev"><Icon name="arrow" size={16} /></span>
            </div>
          </div>
        </div>
      </div>

      <div className="set-card">
        <h3>Connected accounts</h3>
        <p className="sub">Sign in faster and sync your work.</p>
        {[['GitHub', 'globe', true], ['Google', 'globe', true], ['Figma', 'palette', false]].map(([n, ic, conn]) =>
          <div className="set-row" key={n}>
            <div className="cat-tile-ico" style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--surface-2)', color: 'var(--text)' }}><Icon name={ic} size={18} /></div>
            <div className="sr-meta"><b>{n}</b><span>{conn ? 'Connected' : 'Not connected'}</span></div>
            <button className="btn btn-sm" onClick={() => notify(conn ? n + ' disconnected' : n + ' connected')}>{conn ? 'Disconnect' : 'Connect'}</button>
          </div>)}
      </div>

      <div className="set-card">
        <h3>Backup &amp; restore</h3>
        <p className="sub">Your sections, favorites, profile and preferences are {window.storageLabel()}. Export a backup to keep them safe or move them to another browser or device.</p>
        <div className="set-row" style={{ borderTop: '1px solid var(--border)' }}>
          <div className="cat-tile-ico" style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--surface-2)', color: 'var(--text)' }}><Icon name="download" size={18} /></div>
          <div className="sr-meta"><b>Export backup</b><span>{backupSummary}</span></div>
          <button className="btn btn-sm" onClick={() => { exportAppData(); notify('Backup downloaded'); }}><Icon name="download" size={15} /> Export</button>
        </div>
        <div className="set-row">
          <div className="cat-tile-ico" style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--surface-2)', color: 'var(--text)' }}><Icon name="upload" size={18} /></div>
          <div className="sr-meta"><b>Restore from backup</b><span>Import a .json backup file. This replaces matching data, then reloads.</span></div>
          <input ref={importRef} type="file" accept="application/json,.json" style={{ display: 'none' }}
            onChange={(e) => { const f = e.target.files[0]; e.target.value = ''; if (!f) return;
              importAppData(f, (ok, n) => { if (ok) { notify('Restored ' + n + ' items \u2014 reloading\u2026'); setTimeout(() => location.reload(), 900); } else { notify('That file isn\u2019t a valid backup', true); } }); }} />
          <button className="btn btn-sm" onClick={() => importRef.current.click()}><Icon name="upload" size={15} /> Import</button>
        </div>
      </div>

      <div className="set-foot">
        <button className="btn btn-primary" onClick={() => { setProfile({ lang, tz }); notify('Account settings saved'); }}><Icon name="save" size={16} /> Save changes</button>
      </div>
    </>
  );
}

/* ---------- Appearance (wired to live tweaks) ---------- */
function AppearanceTab({ t, setTweak, notify }) {
  const accents = ['#1a7fff', '#6366f1', '#10b981', '#f97316', '#ec4899', '#8b5cf6'];
  return (
    <>
      <div className="set-card">
        <h3>Theme</h3>
        <p className="sub">Switch between light and dark — applies instantly.</p>
        <div className="set-seg">
          <button className={t.theme === 'light' ? 'active' : ''} onClick={() => setTweak('theme', 'light')}><Icon name="sun" size={15} /> Light</button>
          <button className={t.theme === 'dark' ? 'active' : ''} onClick={() => setTweak('theme', 'dark')}><Icon name="moon" size={15} /> Dark</button>
        </div>
      </div>

      <div className="set-card">
        <h3>Accent color</h3>
        <p className="sub">Used across buttons, links and highlights.</p>
        <div className="set-swatches">
          {accents.map(c =>
            <span key={c} className={'set-swatch' + (t.accent === c ? ' active' : '')} style={{ background: c }} onClick={() => setTweak('accent', c)} />)}
        </div>
      </div>

      <div className="set-card">
        <h3>Density</h3>
        <p className="sub">Control spacing in the section grid.</p>
        <div className="set-seg">
          {['compact', 'regular', 'comfy'].map(d =>
            <button key={d} className={t.density === d ? 'active' : ''} onClick={() => setTweak('density', d)} style={{ textTransform: 'capitalize' }}>{d}</button>)}
        </div>
      </div>

      <div className="set-card">
        <h3>Typography</h3>
        <p className="sub">Pick a font pairing for the interface.</p>
        <div className="set-seg">
          {[['modern', 'Modern'], ['geometric', 'Geometric'], ['playful', 'Playful']].map(([v, l]) =>
            <button key={v} className={t.fontPair === v ? 'active' : ''} onClick={() => setTweak('fontPair', v)}>{l}</button>)}
        </div>
      </div>
    </>
  );
}

/* ---------- Notifications ---------- */
function NotificationsTab({ profile, setProfile, notify }) {
  const n = profile.notif || {};
  const toggle = (k) => setProfile(p => Object.assign({}, p, { notif: Object.assign({}, p.notif, { [k]: !p.notif[k] }) }));
  const rows = [
    ['product', 'Product updates', 'New sections, features and improvements.'],
    ['weekly', 'Weekly digest', 'A summary of fresh sections every Monday.'],
    ['mentions', 'Comments & mentions', 'When someone replies to or mentions you.'],
    ['marketing', 'Tips & offers', 'Occasional product tips and promotions.']
  ];
  return (
    <div className="set-card">
      <h3>Email notifications</h3>
      <p className="sub">Choose what lands in your inbox. Saved automatically.</p>
      {rows.map(([k, title, desc]) =>
        <div className="set-row" key={k}>
          <div className="sr-meta"><b>{title}</b><span>{desc}</span></div>
          <Switch on={!!n[k]} onClick={() => { toggle(k); notify('Preference updated'); }} />
        </div>)}
    </div>
  );
}

/* ---------- Billing ---------- */
function BillingTab({ favs, nav, notify }) {
  const customCount = window.SectionStore.list().length;
  const used = Math.min(40, customCount + (favs ? favs.length : 0));
  return (
    <>
      <div className="set-card">
        <h3>Current plan</h3>
        <p className="sub">You're on the Pro trial.</p>
        <div className="plan-card">
          <div className="pc-ico"><Icon name="star" size={22} /></div>
          <div className="pc-meta"><b>Pro — Trial</b><span>9 days remaining · renews at $19/mo</span></div>
          <button className="btn btn-primary" onClick={() => notify('Redirecting to checkout…')}>Upgrade now</button>
        </div>
        <div className="set-row" style={{ borderTop: '1px solid var(--border)' }}>
          <div className="sr-meta" style={{ flex: 1 }}>
            <b>Favorites &amp; custom sections</b>
            <div className="usage-bar"><i style={{ width: (used / 40 * 100) + '%' }} /></div>
            <span>{used} of 40 used on the free tier</span>
          </div>
        </div>
      </div>

      <div className="set-card">
        <h3>Payment method</h3>
        <p className="sub">Used for your subscription after the trial.</p>
        <div className="set-row">
          <div className="cat-tile-ico" style={{ width: 44, height: 32, borderRadius: 7, background: 'var(--surface-2)', color: 'var(--text)' }}><Icon name="card" size={18} /></div>
          <div className="sr-meta"><b>Visa ending 4242</b><span>Expires 08 / 27</span></div>
          <button className="btn btn-sm" onClick={() => notify('Update payment method')}>Update</button>
        </div>
      </div>

      <div className="set-card">
        <h3>Billing history</h3>
        <p className="sub">Your recent invoices.</p>
        {[['Jun 1, 2026', '$19.00', 'Pro monthly'], ['May 1, 2026', '$19.00', 'Pro monthly'], ['Apr 1, 2026', '$0.00', 'Trial started']].map(([d, amt, desc], i) =>
          <div className="set-row" key={i}>
            <div className="sr-meta"><b>{desc}</b><span>{d}</span></div>
            <span style={{ fontWeight: 600, fontSize: 14, marginRight: 14 }}>{amt}</span>
            <button className="act-btn icon-only" title="Download invoice" onClick={() => notify('Invoice downloaded')}><Icon name="download" size={15} /></button>
          </div>)}
      </div>
    </>
  );
}

/* ---------- Security ---------- */
function SecurityTab({ profile, setProfile, notify }) {
  const [pw, setPw] = useState({ cur: '', next: '', conf: '' });
  const canSave = pw.cur && pw.next.length >= 8 && pw.next === pw.conf;
  return (
    <>
      <div className="set-card">
        <h3>Password</h3>
        <p className="sub">Use at least 8 characters.</p>
        <div className="field"><label>Current password</label><input className="t-input" type="password" value={pw.cur} onChange={e => setPw(p => ({ ...p, cur: e.target.value }))} placeholder="••••••••" /></div>
        <div className="set-grid2" style={{ marginTop: 16 }}>
          <div className="field"><label>New password</label><input className="t-input" type="password" value={pw.next} onChange={e => setPw(p => ({ ...p, next: e.target.value }))} placeholder="••••••••" /></div>
          <div className="field"><label>Confirm new</label><input className="t-input" type="password" value={pw.conf} onChange={e => setPw(p => ({ ...p, conf: e.target.value }))} placeholder="••••••••" /></div>
        </div>
        {pw.next && pw.next.length < 8 && <p className="field-err">Password must be at least 8 characters.</p>}
        {pw.conf && pw.next !== pw.conf && <p className="field-err">Passwords don't match.</p>}
        <div style={{ marginTop: 16 }}>
          <button className="btn btn-primary" disabled={!canSave} style={!canSave ? { opacity: .5, cursor: 'not-allowed' } : {}}
            onClick={() => { setPw({ cur: '', next: '', conf: '' }); notify('Password updated'); }}>Update password</button>
        </div>
      </div>

      <div className="set-card">
        <h3>Two-factor authentication</h3>
        <p className="sub">Add an extra layer of security at sign-in.</p>
        <div className="set-row">
          <div className="sr-meta"><b>Authenticator app</b><span>{profile.twoFactor ? 'Enabled' : 'Currently disabled'}</span></div>
          <Switch on={!!profile.twoFactor} onClick={() => { setProfile({ twoFactor: !profile.twoFactor }); notify(profile.twoFactor ? '2FA disabled' : '2FA enabled'); }} />
        </div>
      </div>

      <div className="set-card">
        <h3>Active sessions</h3>
        <p className="sub">Devices currently signed in.</p>
        {[['MacBook Pro · Dhaka', 'This device · active now', true], ['iPhone 15 · Dhaka', 'Last active 2h ago', false]].map(([d, meta, cur], i) =>
          <div className="set-row" key={i}>
            <div className="cat-tile-ico" style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--surface-2)', color: 'var(--text)' }}><Icon name={i === 0 ? 'desktop' : 'device'} size={18} /></div>
            <div className="sr-meta"><b>{d}</b><span>{meta}</span></div>
            {cur ? <span className="badge" style={{ color: '#1a9d5a' }}>Current</span>
              : <button className="act-btn danger" onClick={() => notify('Session revoked')}>Revoke</button>}
          </div>)}
      </div>

      <div className="set-card danger-card">
        <h3>Delete account</h3>
        <p className="sub">Permanently remove your account and all custom sections. This can't be undone.</p>
        <button className="btn" style={{ color: '#ef4444', borderColor: 'color-mix(in srgb,#ef4444 30%,var(--border))' }}
          onClick={() => notify('Account deletion requires email confirmation', true)}><Icon name="trash" size={15} /> Delete my account</button>
      </div>
    </>
  );
}

Object.assign(window, { SettingsView });
