/* MY GENI — Phase 22 · Settings Workspace v2
 *
 * Nine sections. All fully mock. Every mock action provides visible UI
 * feedback (inline confirmation with a "prototype" chip) so no button
 * looks dead. Depth cap: 1 (Settings → section, switched inline).
 *
 * Routes: #/settings, #/settings/<section-key>
 */

const SETTINGS_SECTIONS = [
  { key: 'workspace',     label: 'Workspace',       icon: 'building' },
  { key: 'people',        label: 'People & roles',  icon: 'users' },
  { key: 'preferences',   label: 'Preferences',     icon: 'settings' },
  { key: 'notifications', label: 'Notifications',   icon: 'bell' },
  { key: 'integrations',  label: 'Integrations',    icon: 'plug' },
  { key: 'data',          label: 'Data & export',   icon: 'download' },
  { key: 'api',           label: 'API & tokens',    icon: 'key' },
  { key: 'audit',         label: 'Audit',           icon: 'clock' },
  { key: 'billing',       label: 'Billing & plan',  icon: 'creditCard' },
];

function SettingsWorkspaceV2({ data, subId }) {
  const active = SETTINGS_SECTIONS.find(s => s.key === subId) || SETTINGS_SECTIONS[0];
  const [toast, setToast] = React.useState(null);

  function showToast(text) {
    setToast({ id: Date.now(), text });
    setTimeout(() => setToast(t => (t && t.text === text ? null : t)), 3200);
  }

  return (
    <main className="main sw2-main" data-screen-label={`15 Settings · ${active.label}`}>
      <div className="sw2-header">
        <div>
          <h1 className="greeting">Settings</h1>
          <div className="date-line">
            Workspace preferences and mock controls · <span className="mono">local prototype</span>
          </div>
        </div>
      </div>

      <div className="sw2-grid">
        {/* Section rail */}
        <nav className="sw2-rail" aria-label="Settings sections">
          {SETTINGS_SECTIONS.map(s => (
            <a key={s.key}
               href={`#/settings/${s.key}`}
               className={`sw2-rail-item ${s.key === active.key ? 'active' : ''}`}>
              <SW2Icon name={s.icon} />
              <span>{s.label}</span>
            </a>
          ))}
        </nav>

        {/* Section body */}
        <div className="sw2-body">
          {active.key === 'workspace'     && <SW2Workspace     data={data} showToast={showToast} />}
          {active.key === 'people'        && <SW2People        data={data} showToast={showToast} />}
          {active.key === 'preferences'   && <SW2Preferences   showToast={showToast} />}
          {active.key === 'notifications' && <SW2Notifications showToast={showToast} />}
          {active.key === 'integrations'  && <SW2Integrations  showToast={showToast} />}
          {active.key === 'data'          && <SW2Data          data={data} showToast={showToast} />}
          {active.key === 'api'           && <SW2Api           showToast={showToast} />}
          {active.key === 'audit'         && <SW2Audit         data={data} />}
          {active.key === 'billing'       && <SW2Billing       showToast={showToast} />}
        </div>
      </div>

      {/* Toast */}
      {toast && (
        <div className="sw2-toast" role="status">
          <span className="sw2-toast-icon">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M5 12l4 4L19 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </span>
          <span className="sw2-toast-text">{toast.text}</span>
          <span className="sw2-toast-chip">local prototype</span>
        </div>
      )}
    </main>
  );
}

function SW2Icon({ name }) {
  const size = 16;
  const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', strokeWidth: '1.7', stroke: 'currentColor', strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'building':   return <svg {...props}><path d="M4 21V6a2 2 0 012-2h6v17M14 21V10h4a2 2 0 012 2v9M4 21h16"/><path d="M8 9h1M8 13h1M8 17h1"/></svg>;
    case 'users':      return <svg {...props}><path d="M17 21v-2a4 4 0 00-4-4H7a4 4 0 00-4 4v2M9 11a4 4 0 100-8 4 4 0 000 8zM21 21v-2a4 4 0 00-3-3.87M17 3.13A4 4 0 0117 11"/></svg>;
    case 'settings':   return <svg {...props}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 11-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09a1.65 1.65 0 00-1-1.51 1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09a1.65 1.65 0 001.51-1 1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 112.83-2.83l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9c.36.14.68.35.94.63.28.26.49.58.63.94V15z"/></svg>;
    case 'bell':       return <svg {...props}><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0"/></svg>;
    case 'plug':       return <svg {...props}><path d="M12 22v-5M9 8V2M15 8V2M6 16v-3a4 4 0 014-4h4a4 4 0 014 4v3H6z"/></svg>;
    case 'download':   return <svg {...props}><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>;
    case 'key':        return <svg {...props}><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 11-7.778 7.778 5.5 5.5 0 017.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>;
    case 'clock':      return <svg {...props}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>;
    case 'creditCard': return <svg {...props}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg>;
    default:           return <svg {...props}><circle cx="12" cy="12" r="10"/></svg>;
  }
}

// ---- Section: Workspace ------------------------------------------
function SW2Workspace({ data, showToast }) {
  const [name, setName] = React.useState('My Geni');
  const [tagline, setTagline] = React.useState('Product Operating System');
  const [tz, setTz] = React.useState('Asia/Tehran');
  return (
    <SW2Panel title="Workspace" hint="Identity and defaults for the MY GENI workspace.">
      <SW2Field label="Workspace name">
        <input className="sw2-input" value={name} onChange={(e) => setName(e.target.value)} />
      </SW2Field>
      <SW2Field label="Tagline">
        <input className="sw2-input" value={tagline} onChange={(e) => setTagline(e.target.value)} />
      </SW2Field>
      <SW2Field label="Default timezone">
        <select className="sw2-input" value={tz} onChange={(e) => setTz(e.target.value)}>
          <option>Asia/Tehran</option>
          <option>UTC</option>
          <option>Europe/London</option>
          <option>America/New_York</option>
          <option>America/Los_Angeles</option>
        </select>
      </SW2Field>
      <SW2Field label="Workspace mark">
        <div className="sw2-mark-preview">
          <div className="sw2-mark">MY</div>
          <div className="sw2-mark-meta">
            <div>Vector SVG · uses currentColor · scales cleanly at every size.</div>
            <button className="btn btn-white btn-sm" onClick={() => showToast('Mark upload is prototype-only.')}>Upload custom mark</button>
          </div>
        </div>
      </SW2Field>
      <SW2Actions>
        <button className="btn btn-primary btn-sm" onClick={() => showToast('Workspace preferences saved.')}>Save changes</button>
      </SW2Actions>
    </SW2Panel>
  );
}

// ---- Section: People & Roles -------------------------------------
function SW2People({ data, showToast }) {
  const team = (window.MYGENI_PEOPLE && window.MYGENI_PEOPLE.team()) || [];
  return (
    <SW2Panel title="People & roles" hint="These are the five MY GENI team members. Roles here are functional workspace labels — not factual titles.">
      <div className="sw2-people">
        {team.map(p => (
          <div key={p.key} className="sw2-person">
            <Avatar name={p.displayName} size="md" />
            <div className="sw2-person-body">
              <div className="sw2-person-name">
                {p.displayName}
                {p.isCurrentUser && <span className="sw2-you-chip">YOU</span>}
              </div>
              <div className="sw2-person-role">{p.functionalRole}</div>
            </div>
            <button className="sw2-person-role-btn" onClick={() => showToast(`Role editor for ${p.displayName} is prototype-only.`)}>
              Edit role
            </button>
          </div>
        ))}
      </div>
      <SW2Note>
        <b>Note:</b> Real job titles have not been supplied by the team. Roles shown above are functional workspace-only labels used to keep the mock coherent. When real titles arrive, editing them here (single source of truth is <span className="mono">people-registry.js</span>) will propagate everywhere in the product.
      </SW2Note>
    </SW2Panel>
  );
}

// ---- Section: Preferences ----------------------------------------
function SW2Preferences({ showToast }) {
  const [theme, setTheme] = React.useState('light');
  const [density, setDensity] = React.useState('comfortable');
  const [lang, setLang] = React.useState('en');
  return (
    <SW2Panel title="Preferences" hint="Your personal experience preferences.">
      <SW2Field label="Theme">
        <SW2Segment value={theme} onChange={(v) => { setTheme(v); showToast(`Theme set to ${v}.`); }} options={[['light','Light'],['dark','Dark (prototype)']]} />
      </SW2Field>
      <SW2Field label="Density">
        <SW2Segment value={density} onChange={(v) => { setDensity(v); showToast(`Density set to ${v}.`); }} options={[['compact','Compact'],['comfortable','Comfortable'],['spacious','Spacious']]} />
      </SW2Field>
      <SW2Field label="Language">
        <select className="sw2-input" value={lang} onChange={(e) => { setLang(e.target.value); showToast('Language preference updated.'); }}>
          <option value="en">English</option>
          <option value="fa">فارسی (Farsi — prototype)</option>
        </select>
      </SW2Field>
      <SW2Field label="Sidebar default">
        <SW2Segment value="collapsed" onChange={() => showToast('Managed by the sidebar toggle · saved automatically.')} options={[['collapsed','Collapsed'],['expanded','Expanded']]} />
      </SW2Field>
    </SW2Panel>
  );
}

// ---- Section: Notifications --------------------------------------
function SW2Notifications({ showToast }) {
  const [toggles, setToggles] = React.useState({
    inbox: true, mentions: true, waiting: false, digest: true, mobile: false,
  });
  function flip(k, label) {
    setToggles(t => ({ ...t, [k]: !t[k] }));
    showToast(`${label} ${toggles[k] ? 'muted' : 'enabled'}.`);
  }
  return (
    <SW2Panel title="Notifications" hint="Choose which surfaces send you signal.">
      <SW2Toggle checked={toggles.inbox}    onChange={() => flip('inbox',    'Inbox alerts')}     label="Inbox alerts"        sub="When someone requests your action or review."/>
      <SW2Toggle checked={toggles.mentions} onChange={() => flip('mentions', 'Mentions')}         label="Mentions"            sub="When you're mentioned in a comment or activity."/>
      <SW2Toggle checked={toggles.waiting}  onChange={() => flip('waiting',  'Waiting-on nudges')} label="Waiting-on nudges"   sub="Prompt me when I've been waiting on someone for 3+ days."/>
      <SW2Toggle checked={toggles.digest}   onChange={() => flip('digest',   'Weekly digest')}    label="Weekly digest"       sub="Monday morning summary of last week + this week's focus."/>
      <SW2Toggle checked={toggles.mobile}   onChange={() => flip('mobile',   'Mobile push')}      label="Mobile push"         sub="Push notifications on the MY GENI mobile app (prototype)."/>
    </SW2Panel>
  );
}

// ---- Section: Integrations ---------------------------------------
function SW2Integrations({ showToast }) {
  const items = [
    { key: 'slack',   name: 'Slack',   status: 'not-connected', desc: 'Route Inbox items and decisions to a workspace channel.' },
    { key: 'github',  name: 'GitHub',  status: 'connected',     desc: 'Link Systems and Development items to PRs and issues.' },
    { key: 'linear',  name: 'Linear',  status: 'not-connected', desc: 'Optional canonical sync for Work items.' },
    { key: 'figma',   name: 'Figma',   status: 'connected',     desc: 'Embed design frames in Design item previews.' },
    { key: 'notion',  name: 'Notion',  status: 'not-connected', desc: 'Import legacy freeform briefs during migration.' },
  ];
  return (
    <SW2Panel title="Integrations" hint="Connect external tools. All actions are prototype-only.">
      <div className="sw2-integrations">
        {items.map(i => (
          <div key={i.key} className="sw2-integration">
            <div className="sw2-integration-glyph">{i.name.slice(0, 1)}</div>
            <div className="sw2-integration-body">
              <div className="sw2-integration-name">{i.name}</div>
              <div className="sw2-integration-desc">{i.desc}</div>
            </div>
            <button
              className={`btn btn-sm ${i.status === 'connected' ? 'btn-white' : 'btn-primary'}`}
              onClick={() => showToast(`${i.name} ${i.status === 'connected' ? 'disconnect' : 'connect'} flow is prototype-only.`)}
            >
              {i.status === 'connected' ? 'Manage' : 'Connect'}
            </button>
          </div>
        ))}
      </div>
    </SW2Panel>
  );
}

// ---- Section: Data & Export --------------------------------------
function SW2Data({ data, showToast }) {
  function downloadJson() {
    const blob = new Blob([JSON.stringify({ mygeni: data, exportedAt: new Date().toISOString() }, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'mygeni-workspace-export.json';
    document.body.appendChild(a); a.click(); a.remove();
    URL.revokeObjectURL(url);
    showToast('Workspace snapshot downloaded as JSON.');
  }
  return (
    <SW2Panel title="Data & export" hint="Export canonical workspace data. The download below is real — it serializes the live client-side dataset.">
      <div className="sw2-actions-grid">
        <button className="sw2-action-card" onClick={downloadJson}>
          <SW2Icon name="download" />
          <div>
            <div className="sw2-action-title">Download workspace JSON</div>
            <div className="sw2-action-sub">Includes projects, decisions, work items, documents · this actually works</div>
          </div>
        </button>
        <button className="sw2-action-card" onClick={() => showToast('CSV export is prototype-only.')}>
          <SW2Icon name="download" />
          <div>
            <div className="sw2-action-title">Export Decisions log · CSV</div>
            <div className="sw2-action-sub">Structured log with owner, evidence, and status</div>
          </div>
        </button>
        <button className="sw2-action-card" onClick={() => showToast('Archive request submitted (prototype).')}>
          <SW2Icon name="download" />
          <div>
            <div className="sw2-action-title">Request full archive</div>
            <div className="sw2-action-sub">Includes attached documents and audit trail</div>
          </div>
        </button>
      </div>
    </SW2Panel>
  );
}

// ---- Section: API & Tokens ---------------------------------------
function SW2Api({ showToast }) {
  const [revealed, setRevealed] = React.useState(false);
  const token = 'mg_live_9d4c1e0f3b7a2c5d8e6a1f0b';
  return (
    <SW2Panel title="API & tokens" hint="Programmatic access to the MY GENI workspace. Tokens here are prototype-only.">
      <div className="sw2-token-card">
        <div className="sw2-token-head">
          <div>
            <div className="sw2-token-name">Personal access token</div>
            <div className="sw2-token-sub">Scopes: <span className="mono">read:*</span></div>
          </div>
          <button className="btn btn-white btn-sm" onClick={() => showToast('Token revoke flow is prototype-only.')}>Revoke</button>
        </div>
        <div className="sw2-token-value">
          <span className="mono">{revealed ? token : '••••••••••••••••••••••••'}</span>
          <button className="sw2-token-btn" onClick={() => setRevealed(v => !v)}>{revealed ? 'Hide' : 'Reveal'}</button>
          <button className="sw2-token-btn" onClick={() => {
            navigator.clipboard?.writeText(token);
            showToast('Token copied to clipboard.');
          }}>Copy</button>
        </div>
      </div>
      <button className="btn btn-primary btn-sm" style={{ marginTop: 16 }} onClick={() => showToast('New token creation is prototype-only.')}>
        Create new token
      </button>
    </SW2Panel>
  );
}

// ---- Section: Audit ----------------------------------------------
function SW2Audit({ data }) {
  const rows = [
    { when: 'Today · 10:14', who: 'Keyvan',       what: 'Resolved copy feedback on Smart Project Brief · Desktop.' },
    { when: 'Today · 09:22', who: 'Alireza Izadi', what: 'Signed in.' },
    { when: 'Yesterday · 16:42', who: 'Alireza Izadi', what: 'Requested one navigation change on Desktop.' },
    { when: 'Sep 14 · 14:12', who: 'Alireza Izadi', what: 'Decided: Structured project brief vs freeform document.' },
    { when: 'Sep 12 · 11:04', who: 'Alireza Izadi', what: 'Moved AI weekly digest to Review.' },
    { when: 'Sep 12',        who: 'Devon',          what: 'Finalized SLM-first inference decision.' },
  ];
  return (
    <SW2Panel title="Audit" hint="Recent workspace activity. Snapshot from canonical activity feed.">
      <div className="sw2-audit">
        {rows.map((r, i) => (
          <div key={i} className="sw2-audit-row">
            <div className="sw2-audit-when mono">{r.when}</div>
            <div className="sw2-audit-who"><Avatar name={r.who} size="xs" /> {r.who}</div>
            <div className="sw2-audit-what">{r.what}</div>
          </div>
        ))}
      </div>
    </SW2Panel>
  );
}

// ---- Section: Billing --------------------------------------------
function SW2Billing({ showToast }) {
  return (
    <SW2Panel title="Billing & plan" hint="Prototype pricing preview. No card charged.">
      <div className="sw2-plan-card">
        <div className="sw2-plan-head">
          <div>
            <div className="sw2-plan-eyebrow">CURRENT PLAN</div>
            <div className="sw2-plan-name">Founding team</div>
          </div>
          <div className="sw2-plan-price">
            <div className="sw2-plan-num">$0</div>
            <div className="sw2-plan-cycle">/ mo · while internal</div>
          </div>
        </div>
        <ul className="sw2-plan-features">
          <li>5 seats — the founding team</li>
          <li>Unlimited projects, decisions, and documents</li>
          <li>Local prototype — no external billing</li>
        </ul>
        <div className="sw2-plan-actions">
          <button className="btn btn-white btn-sm" onClick={() => showToast('Plan comparison is prototype-only.')}>Compare plans</button>
          <button className="btn btn-primary btn-sm" onClick={() => showToast('Upgrade flow is prototype-only.')}>Upgrade when ready</button>
        </div>
      </div>
    </SW2Panel>
  );
}

// ---- Shared primitives -------------------------------------------
function SW2Panel({ title, hint, children }) {
  return (
    <div className="sw2-panel">
      <div className="sw2-panel-head">
        <h3 className="sw2-panel-title">{title}</h3>
        {hint && <p className="sw2-panel-hint">{hint}</p>}
      </div>
      <div className="sw2-panel-body">{children}</div>
    </div>
  );
}
function SW2Field({ label, children }) {
  return (
    <div className="sw2-field">
      <label className="sw2-field-label">{label}</label>
      <div className="sw2-field-control">{children}</div>
    </div>
  );
}
function SW2Actions({ children }) {
  return <div className="sw2-panel-actions">{children}</div>;
}
function SW2Segment({ value, onChange, options }) {
  return (
    <div className="sw2-segment">
      {options.map(([v, label]) => (
        <button key={v}
                type="button"
                className={`sw2-segment-btn ${v === value ? 'active' : ''}`}
                onClick={() => onChange(v)}>
          {label}
        </button>
      ))}
    </div>
  );
}
function SW2Toggle({ checked, onChange, label, sub }) {
  return (
    <div className="sw2-toggle-row">
      <div className="sw2-toggle-body">
        <div className="sw2-toggle-label">{label}</div>
        {sub && <div className="sw2-toggle-sub">{sub}</div>}
      </div>
      <button type="button"
              role="switch"
              aria-checked={checked}
              className={`sw2-toggle ${checked ? 'on' : 'off'}`}
              onClick={onChange}>
        <span className="sw2-toggle-thumb" />
      </button>
    </div>
  );
}
function SW2Note({ children }) {
  return <div className="sw2-note">{children}</div>;
}

Object.assign(window, { SettingsWorkspaceV2 });
