// SETTINGS PLATFORM — entry
// 6 primary tabs + pill sub-tabs with full infrastructure wiring:
//   cmdK search · URL hash deep-linking · keyboard nav · skeleton · unsaved guard
//   · toast/undo · compliance drawer · settings-as-code export · audit trail

const { useState: useSpState, useEffect: useSpEffect, useRef: useSpRef } = React;
const Tspl = window.ArbiterTokens;

const STG_GROUPS = [
  { id: 'you', label: 'You', subs: [
    { id: 'profile',       label: 'Profile' },
    { id: 'account',       label: 'Account' },
    { id: 'preferences',   label: 'Preferences' },
    { id: 'notifications', label: 'Notifications' },
  ]},
  { id: 'firm', label: 'Firm', subs: [
    { id: 'firm',  label: 'Firm' },
    { id: 'users', label: 'Users' },
    { id: 'teams', label: 'Teams' },
    { id: 'roles', label: 'Roles' },
  ]},
  { id: 'security', label: 'Security', subs: [
    { id: 'security',   label: 'Security' },
    { id: 'audit',      label: 'Audit Log' },
    { id: 'compliance', label: 'Compliance' },
  ]},
  { id: 'integrations', label: 'Integrations', subs: [
    { id: 'integrations', label: 'Integrations' },
    { id: 'api',          label: 'API & Webhooks' },
    { id: 'email',        label: 'Email' },
  ]},
  { id: 'data', label: 'Data', subs: [
    { id: 'retention',    label: 'Retention' },
    { id: 'fields',       label: 'Custom Fields' },
    { id: 'templates',    label: 'Templates' },
    { id: 'importexport', label: 'Import / Export' },
  ]},
  { id: 'system', label: 'System', subs: [
    { id: 'billing', label: 'Billing' },
    { id: 'health',  label: 'System Health' },
  ]},
];

function SettingsPlatformInner() {
  const infra = window.__stg_infra;
  const { useToast, useDirty, DirtyFooter, InfoTip, SettingsSearch, SETTINGS_SEARCH_INDEX,
          parseSettingsHash, setSettingsHash, ComplianceBreakdownDrawer, downloadSettingsAsCode } = infra;

  // Initialize from URL hash if present
  const initial = (() => {
    const parsed = parseSettingsHash();
    if (parsed && STG_GROUPS.find(g => g.id === parsed.primary)) {
      const g = STG_GROUPS.find(g => g.id === parsed.primary);
      if (g.subs.find(s => s.id === parsed.sub)) return { primary: parsed.primary, sub: parsed.sub };
      return { primary: parsed.primary, sub: g.subs[0].id };
    }
    return { primary: 'you', sub: 'profile' };
  })();

  const [activeGroup, setActiveGroup] = useSpState(initial.primary);
  const [subByGroup, setSubByGroup] = useSpState(() => {
    const init = {};
    STG_GROUPS.forEach(g => { init[g.id] = g.subs[0].id; });
    init[initial.primary] = initial.sub;
    return init;
  });
  const [searchOpen, setSearchOpen] = useSpState(false);
  const [complianceDrawer, setComplianceDrawer] = useSpState(false);
  const [loading, setLoading] = useSpState(false);
  const tabStripRef = useSpRef(null);
  const pillStripRef = useSpRef(null);
  const toast = useToast();
  const { dirty } = useDirty();

  const stg = window.__stg;
  const data = window.SETTINGS_DATA;
  const k = data.kpis;

  const group = STG_GROUPS.find(g => g.id === activeGroup);
  const activeSub = subByGroup[group.id];

  // ─── URL hash sync ───
  useSpEffect(() => {
    setSettingsHash(activeGroup, activeSub);
    // Skeleton flash on navigation (simulated fetch)
    setLoading(true);
    const h = setTimeout(() => setLoading(false), 180);
    return () => clearTimeout(h);
  }, [activeGroup, activeSub]);

  // ─── Back/forward support ───
  useSpEffect(() => {
    const h = () => {
      const parsed = parseSettingsHash();
      if (!parsed) return;
      const g = STG_GROUPS.find(x => x.id === parsed.primary);
      if (!g) return;
      setActiveGroup(parsed.primary);
      if (parsed.sub && g.subs.find(s => s.id === parsed.sub)) {
        setSubByGroup(prev => ({ ...prev, [parsed.primary]: parsed.sub }));
      }
    };
    window.addEventListener('hashchange', h);
    return () => window.removeEventListener('hashchange', h);
  }, []);

  // ─── cmdK / Ctrl+K ───
  useSpEffect(() => {
    const h = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setSearchOpen(true);
      } else if (e.key === '/' && document.activeElement === document.body) {
        e.preventDefault();
        setSearchOpen(true);
      }
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  const handleJump = (item) => {
    const t = item.target;
    if (dirty && !window.confirm('You have unsaved changes. Discard them?')) return;
    setActiveGroup(t.primary);
    setSubByGroup(prev => ({ ...prev, [t.primary]: t.sub }));
    if (t.anchor) setTimeout(() => {
      const el = document.querySelector(`[data-anchor="${t.anchor}"]`);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 300);
  };

  // ─── Keyboard nav on tab strips (#27) ───
  const handleTabKey = (e, list, currentId, setId) => {
    if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft' && e.key !== 'Home' && e.key !== 'End') return;
    e.preventDefault();
    const idx = list.findIndex(x => x.id === currentId);
    let next = idx;
    if (e.key === 'ArrowRight') next = Math.min(list.length - 1, idx + 1);
    else if (e.key === 'ArrowLeft') next = Math.max(0, idx - 1);
    else if (e.key === 'Home') next = 0;
    else if (e.key === 'End') next = list.length - 1;
    setId(list[next].id);
  };

  const renderSub = () => {
    if (loading) {
      return (
        <div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(200px, 100%), 1fr))', gap: '10px', marginBottom: '16px' }}>
            {[1,2,3,4].map(i => <infra.Skeleton key={i} height="72px" radius="8px" />)}
          </div>
          <infra.Skeleton height="32px" radius="6px" style={{ marginBottom: '12px' }} />
          <infra.Skeleton height="260px" radius="8px" />
        </div>
      );
    }
    switch (activeSub) {
      case 'profile':       return <window.SettingsProfile data={data} />;
      case 'account':       return <window.SettingsAccount data={data} />;
      case 'preferences':   return <window.SettingsPreferences data={data} />;
      case 'notifications': return <window.SettingsNotifications data={data} />;
      case 'firm':          return <window.SettingsFirm data={data} />;
      case 'users':         return <window.SettingsUsers data={data} />;
      case 'teams':         return <window.SettingsTeams data={data} />;
      case 'roles':         return <window.SettingsRoles data={data} />;
      case 'security':      return <window.SettingsSecurity data={data} />;
      case 'audit':         return <window.SettingsAuditLog data={data} />;
      case 'compliance':    return <window.SettingsCompliance data={data} />;
      case 'integrations':  return <window.SettingsIntegrations data={data} />;
      case 'api':           return <window.SettingsAPIWebhooks data={data} />;
      case 'email':         return <window.SettingsEmail data={data} />;
      case 'retention':     return <window.SettingsDataRetention data={data} />;
      case 'fields':        return <window.SettingsCustomFields data={data} />;
      case 'templates':     return <window.SettingsTemplates data={data} />;
      case 'importexport':  return <window.SettingsImportExport data={data} />;
      case 'billing':       return <window.SettingsBilling data={data} />;
      case 'health':        return <window.SettingsSystem data={data} />;
      default:              return <window.SettingsProfile data={data} />;
    }
  };

  const kpiChip = (label, value, onClick, accent) => (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: '8px',
      padding: '6px 14px', borderRadius: '8px',
      background: accent?.bg || Tspl.color.bg.secondary,
      border: `1px solid ${accent?.border || Tspl.color.border.light}`,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <span style={{ fontSize: '10px', fontWeight: 600, color: accent?.fg || Tspl.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{label}</span>
      <span style={{ fontSize: '14px', fontWeight: 700, color: accent?.fg || Tspl.color.text.primary, fontFamily: Tspl.font.mono }}>{value}</span>
    </div>
  );

  const subTabStyle = (active) => ({
    padding: '8px 14px', fontSize: '11px',
    fontWeight: active ? 700 : 500,
    color: active ? '#fff' : Tspl.color.text.tertiary,
    background: active ? stg.steelDeep : 'transparent',
    border: `1px solid ${active ? stg.steelDeep : Tspl.color.border.medium}`,
    borderRadius: '6px', cursor: 'pointer',
    letterSpacing: '0.02em', whiteSpace: 'nowrap',
    fontFamily: Tspl.font.family, transition: 'all 0.15s',
    outline: 'none',
  });

  return (
    <div style={{ ...stg.container, display: 'flex', flexDirection: 'column' }}>
      <div style={stg.header}>
        <div style={stg.headerTitle}>
          <div style={stg.icon}>
            {window.Icons && window.Icons.Settings
              ? <window.Icons.Settings size={16} color="#fff" strokeWidth={1.75} />
              : ''}
          </div>
          <div>
            <div style={stg.title}>Settings</div>
            <div style={stg.subtitle}>The control plane — users, security, integrations, governance, compliance</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          {kpiChip('Seats', `${k.seatsUsed}/${k.seats}`, () => { setActiveGroup('system'); setSubByGroup(p => ({ ...p, system: 'billing' })); })}
          {kpiChip('MFA', `${k.mfaCoverage}%`, () => { setActiveGroup('security'); setSubByGroup(p => ({ ...p, security: 'security' })); }, { bg: stg.emeraldBg, border: 'rgba(5,150,105,0.22)', fg: stg.emerald })}
          {kpiChip('Compliance', `${k.complianceScore}%`, () => setComplianceDrawer(true), { bg: stg.violetBg, border: 'rgba(124,58,237,0.22)', fg: stg.violet })}
          <button onClick={() => setSearchOpen(true)} title="Search settings (cmdK)" style={{
            ...stg.btnSecondary, display: 'flex', alignItems: 'center', gap: '6px',
          }}> <span style={{ fontFamily: Tspl.font.mono, fontSize: '10px' }}>cmdK</span></button>
          <button onClick={downloadSettingsAsCode} title="Export all settings as YAML" style={{
            ...stg.btnSecondary, display: 'flex', alignItems: 'center', gap: '6px',
          }}>⇣ YAML</button>
          <button style={stg.btnPrimary}>+ Invite user</button>
        </div>
      </div>

      {/* PRIMARY TABS — keyboard nav + aria-current */}
      <div ref={tabStripRef} role="tablist" aria-label="Settings sections"
        style={{ ...stg.tabs, overflowX: 'auto' }}>
        {STG_GROUPS.map(g => (
          <button
            key={g.id}
            role="tab"
            aria-selected={activeGroup === g.id}
            aria-current={activeGroup === g.id ? 'page' : undefined}
            tabIndex={activeGroup === g.id ? 0 : -1}
            onClick={() => setActiveGroup(g.id)}
            onKeyDown={(e) => handleTabKey(e, STG_GROUPS, activeGroup, setActiveGroup)}
            style={{ ...stg.tab, ...(activeGroup === g.id ? stg.tabActive : {}) }}
          >
            {g.label}
          </button>
        ))}
      </div>

      {/* PILL SUB-TABS */}
      {group.subs.length > 1 && (
        <div ref={pillStripRef} role="tablist" aria-label={`${group.label} sub-sections`}
          style={{
            display: 'flex', gap: '8px', padding: '14px 24px 2px', flexWrap: 'wrap',
            borderBottom: `1px solid ${Tspl.color.border.light}`,
            background: Tspl.color.bg.secondary,
            flexShrink: 0,
          }}>
          {group.subs.map(s => (
            <button
              key={s.id}
              role="tab"
              aria-selected={activeSub === s.id}
              aria-current={activeSub === s.id ? 'page' : undefined}
              tabIndex={activeSub === s.id ? 0 : -1}
              onClick={() => setSubByGroup({ ...subByGroup, [group.id]: s.id })}
              onKeyDown={(e) => handleTabKey(e, group.subs, activeSub, (id) => setSubByGroup({ ...subByGroup, [group.id]: id }))}
              style={subTabStyle(activeSub === s.id)}
            >
              {s.label}
            </button>
          ))}
        </div>
      )}

      <div style={{ ...stg.body, flex: 1 }}>
        {renderSub()}
      </div>

      <DirtyFooter />

      <SettingsSearch
        open={searchOpen}
        onClose={() => setSearchOpen(false)}
        items={SETTINGS_SEARCH_INDEX}
        onJump={handleJump}
      />

      <ComplianceBreakdownDrawer
        open={complianceDrawer}
        onClose={() => setComplianceDrawer(false)}
      />
    </div>
  );
}

function SettingsPlatform() {
  const { ToastProvider, DirtyProvider } = window.__stg_infra;
  return (
    <ToastProvider>
      <DirtyProvider>
        <SettingsPlatformInner />
      </DirtyProvider>
    </ToastProvider>
  );
}

window.SettingsPlatform = SettingsPlatform;
