// Main App — state machine.
// States: gate → partner (legacy home, rarely used) → handoff → auth-success
//         → customer-picker → admin
//
// URL contract:
//   ?from=portal            skips legacy partner home, starts at handoff
//   ?customer=<id>          pre-select a customer (otherwise picker decides)
//   ?skipGate=1             bypass the password gate (demo iframes)
//
// Theme:
//   Uses [data-theme="dark"] on <html> (matches shared /css/theme.css).
//   Tenant accent color is applied as inline CSS var on <body> once a
//   customer is chosen.

function GMApp() {
  const urlIntent = React.useMemo(() => {
    const u = new URLSearchParams(window.location.search);
    return {
      fromPortal: u.get('from') === 'portal',
      customerId: u.get('customer'),
      skipGate: u.get('skipGate') === '1',
    };
  }, []);

  const [stage, setStage] = React.useState(() => {
    if (!urlIntent.skipGate && sessionStorage.getItem(window.GATE_KEY) !== '1') return 'gate';
    if (urlIntent.fromPortal) return 'handoff';
    const saved = sessionStorage.getItem('gm_stage');
    return saved || 'partner';
  });

  const [customerId, setCustomerId] = React.useState(() => {
    if (urlIntent.fromPortal && urlIntent.customerId) return urlIntent.customerId;
    return sessionStorage.getItem('gm_customer') || null;
  });
  const [personaId, setPersonaId] = React.useState(() => sessionStorage.getItem('gm_persona') || 'partner_admin');
  const [themeMode, setThemeMode] = React.useState(() => localStorage.getItem('gm_theme_mode') || 'light');

  React.useEffect(() => { sessionStorage.setItem('gm_stage', stage); }, [stage]);
  React.useEffect(() => { customerId ? sessionStorage.setItem('gm_customer', customerId) : sessionStorage.removeItem('gm_customer'); }, [customerId]);
  React.useEffect(() => { sessionStorage.setItem('gm_persona', personaId); }, [personaId]);
  React.useEffect(() => { localStorage.setItem('gm_theme_mode', themeMode); }, [themeMode]);

  // Light/dark via the shared attribute so /css/theme.css drives both prototype and site.
  React.useEffect(() => {
    if (themeMode === 'dark') document.documentElement.setAttribute('data-theme', 'dark');
    else document.documentElement.removeAttribute('data-theme');
  }, [themeMode]);

  // Tenant accent — exposed as CSS custom properties on <body>.
  // Falls back to the canonical charcoal when no customer is selected.
  const customer = customerId ? window.GM_CUSTOMERS.find(c => c.id === customerId) : null;
  React.useEffect(() => {
    const body = document.body;
    if (customer) {
      body.style.setProperty('--tenant-accent', customer.accent);
      body.style.setProperty('--tenant-accent-contrast', customer.accentContrast);
      body.style.setProperty('--tenant-accent-soft', customer.accentSoft);
    } else {
      body.style.removeProperty('--tenant-accent');
      body.style.removeProperty('--tenant-accent-contrast');
      body.style.removeProperty('--tenant-accent-soft');
    }
  }, [customer?.id]);

  const persona = window.GM_PERSONAS[personaId] || window.GM_PERSONAS.partner_admin;

  // Transitions
  const onPass = () => setStage(urlIntent.fromPortal ? 'handoff' : 'partner');
  const onHandoffDone = () => setStage('auth-success');
  const onAuthContinue = () => {
    // If a customer was passed in the URL, skip the picker for demo speed.
    if (urlIntent.customerId && window.GM_CUSTOMERS.find(c => c.id === urlIntent.customerId)) {
      setCustomerId(urlIntent.customerId);
      setStage('admin');
    } else {
      setStage('customer-picker');
    }
  };
  const onPickCustomer = (c) => {
    setCustomerId(c.id);
    setStage('admin');
  };
  const onExitWorkspace = () => {
    // Back to the picker by default — matches partner "workspace switcher" pattern.
    // Customer remains set in memory but the picker is the shell around tenants.
    setCustomerId(null);
    setStage('customer-picker');
  };
  const onLaunchFromLegacyHome = (c) => {
    setCustomerId(c.id);
    setStage('handoff');
  };

  if (stage === 'gate') return <GMGate onPass={onPass}/>;
  if (stage === 'partner') return <GMPartnerPortal onLaunch={onLaunchFromLegacyHome}/>;
  if (stage === 'handoff') {
    // Platform-level Guardian Mesh auth — no customer context yet.
    // Customer workspace gets picked later in the picker.
    return <GMHandoff onDone={onHandoffDone}/>;
  }
  if (stage === 'auth-success') return <GMAuthSuccess onContinue={onAuthContinue}/>;
  if (stage === 'customer-picker') return <GMCustomerPicker onPick={onPickCustomer}/>;
  if (stage === 'admin' && customer) {
    return (
      <GMAdminPortal
        customer={customer}
        persona={persona}
        onChangePersona={setPersonaId}
        onExitWorkspace={onExitWorkspace}
        themeMode={themeMode}
        onToggleMode={() => setThemeMode(m => m === 'light' ? 'dark' : 'light')}
      />
    );
  }
  // Safety fallback — if admin state but no customer, bounce to picker.
  return <GMCustomerPicker onPick={onPickCustomer}/>;
}

ReactDOM.createRoot(document.getElementById('root')).render(<GMApp/>);
