// Main App shell
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#4be8ff", "#8b6bff", "#ff7ad9"],
  "density": "comfortable",
  "sidebarStyle": "labeled",
  "showAI": true,
  "showStream": true,
  "userName": "Reza",
  "mode": "simple"
}/*EDITMODE-END*/;

function App() {
  const [page, setPage] = React.useState('dashboard');
  const [selectedAgent, setSelectedAgent] = React.useState(null);
  const [cmdkOpen, setCmdkOpen] = React.useState(false);
  const [aiOpen, setAiOpen] = React.useState(false);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply accent palette
  React.useEffect(() => {
    const root = document.documentElement;
    const p = Array.isArray(t.palette) ? t.palette : ['#4be8ff', '#8b6bff', '#ff7ad9'];
    const [c, v, m] = p;
    root.style.setProperty('--violet', v);
    root.style.setProperty('--cyan', c);
    root.style.setProperty('--magenta', m);
    root.style.setProperty('--accent', v);
    root.style.setProperty('--accent-cy', c);
    root.style.setProperty('--accent-mg', m);
    root.style.setProperty('--iridescent', `linear-gradient(135deg, ${c} 0%, ${v} 50%, ${m} 100%)`);
  }, [t.palette]);

  // ⌘K listener
  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); setCmdkOpen(o => !o); }
      else if (e.key === 'Escape') { setCmdkOpen(false); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const nav = (p, id) => {
    setPage(p);
    if (p === 'agents' && id) setSelectedAgent(id);
    if (p !== 'agents') setSelectedAgent(null);
  };

  // Expose nav + AI panel globally so window.actions can route to them
  React.useEffect(() => {
    window.demiurgeNav = nav;
    window.demiurgeOpenAI = () => setAiOpen(true);
    window.demiurgeOpenCmdk = () => setCmdkOpen(true);
  });

  const appClass = ['app', `mode-${t.mode || 'simple'}`];
  if (t.density === 'compact') appClass.push('compact');
  if (t.sidebarStyle === 'rail') appClass.push('layout-rail');

  const isSimple = (t.mode || 'simple') === 'simple';

  // Sidebar: SIMPLE shows fewer items with friendlier labels.
  // COMMAND shows the full operational nav.
  const navSections = isSimple ? [
    { label: 'YOUR BUSINESS', items: [
      { id: 'dashboard',  label: 'Home',           icon: 'Home',      badge: null },
      { id: 'inbox',      label: 'Messages',       icon: 'Inbox',     badge: { kind: 'live', text: '3' } },
      { id: 'calendar',   label: 'Appointments',   icon: 'Calendar',  badge: null },
      { id: 'contacts',   label: 'Customers',      icon: 'People',    badge: null },
    ]},
    { label: 'GROWTH', items: [
      { id: 'channels',   label: 'Social media',     icon: 'Globe',     badge: null },
      { id: 'campaigns',  label: 'Campaigns',        icon: 'Megaphone', badge: null },
      { id: 'funnels',    label: 'Customer journey', icon: 'Funnel',    badge: null },
      { id: 'workflows',  label: 'Automations',      icon: 'Flow',      badge: null },
    ]},
    { label: 'INSIGHTS', items: [
      { id: 'analytics',  label: 'Insights',         icon: 'Chart',     badge: null },
      { id: 'settings',   label: 'Settings',         icon: 'Settings',  badge: null },
    ]},
  ] : [
    { label: 'GROWTH', items: [
      { id: 'dashboard', label: 'Command Center', icon: 'Home', badge: null },
      { id: 'inbox', label: 'Inbox', icon: 'Inbox', badge: { kind: 'live', text: '3' } },
      { id: 'contacts', label: 'Contacts', icon: 'People', badge: null },
      { id: 'campaigns', label: 'Campaigns', icon: 'Megaphone', badge: null },
      { id: 'channels', label: 'Channels', icon: 'Globe', badge: { kind: 'live', text: '13' } },
      { id: 'funnels', label: 'Funnels', icon: 'Funnel', badge: null },
      { id: 'calendar', label: 'Calendar', icon: 'Calendar', badge: null },
    ]},
    { label: 'AUTOMATION', items: [
      { id: 'mission', label: 'Mission Control', icon: 'Target', badge: { kind: 'live', text: '' } },
      { id: 'agents', label: 'Agents', icon: 'Agent', badge: { text: '8' } },
      { id: 'workflows', label: 'Workflows', icon: 'Flow', badge: null },
      { id: 'persona', label: 'Persona Studio', icon: 'Sparkles', badge: { text: 'NEW' } },
      { id: 'templates', label: 'Templates', icon: 'Book', badge: null },
    ]},
    { label: 'AGENCY', items: [
      { id: 'businesses', label: 'Businesses', icon: 'Trophy', badge: { text: '5' } },
    ]},
    { label: 'PLATFORM', items: [
      { id: 'analytics', label: 'Analytics', icon: 'Chart', badge: null },
      { id: 'integrations', label: 'Integrations', icon: 'Plug', badge: null },
      { id: 'settings', label: 'Settings', icon: 'Settings', badge: null },
    ]},
  ];

  const crumbMap = isSimple ? {
    dashboard: 'Home', inbox: 'Messages', calendar: 'Appointments', contacts: 'Customers',
    channels: 'Social media', campaigns: 'Campaigns', funnels: 'Customer journey',
    workflows: 'Automations', analytics: 'Insights', settings: 'Settings',
    agents: 'Agents', persona: 'Persona Studio', templates: 'Templates',
    integrations: 'Integrations', businesses: 'Businesses', mission: 'Mission Control'
  } : {
    dashboard: 'Command Center', agents: 'Agents', workflows: 'Workflows',
    funnels: 'Funnels', campaigns: 'Campaigns', inbox: 'Inbox', contacts: 'Contacts',
    persona: 'Persona Studio', templates: 'Templates', analytics: 'Analytics',
    integrations: 'Integrations', settings: 'Settings', calendar: 'Calendar',
    businesses: 'Businesses', mission: 'Mission Control', channels: 'Channels',
  };

  // When toggling simple→command on a page that has no simple analog, redirect.
  // When toggling command→simple from an advanced-only page (mission/persona/templates/agents/businesses/integrations),
  // bounce to the dashboard.
  const switchMode = () => {
    const nextMode = isSimple ? 'command' : 'simple';
    setTweak('mode', nextMode);
    if (nextMode === 'simple' && !['dashboard','inbox','calendar','contacts','channels','campaigns','funnels','workflows','analytics','settings'].includes(page)) {
      setPage('dashboard');
    }
  };

  return (
    <div className={appClass.join(' ')} onClick={smartClickHandler}>
      <MatrixCanvas/>
      <ScanPulse/>
      <div className="brand">
        <Icon.Logo className="brand-mark"/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
          <span className="brand-name">Demiurge</span>
          <span className="brand-sub">Systems · ext</span>
        </div>
      </div>

      <div className="topbar">
        <div className="crumbs">
          <span>ext</span>
          <span className="sep">/</span>
          <span className="cur">{crumbMap[page] || page}</span>
        </div>

        <div className="cmd-bar" onClick={() => setCmdkOpen(true)}>
          <Icon.Search style={{ width: 14, height: 14, color: 'var(--text-faint)' }}/>
          <span><span className="cmd-prefix">›</span>&nbsp;&nbsp;{isSimple ? 'Search or ask Demiurge…' : 'Search, navigate, or ask Demiurge…'}</span>
          <span className="kbd">⌘K</span>
        </div>

        {/* Mode switcher */}
        <button className={`mode-switch ${isSimple ? 'simple' : 'command'}`} onClick={switchMode} title={isSimple ? 'Switch to Command Mode — advanced controls' : 'Switch to Simple Mode — friendly overview'}>
          <span className="mode-track">
            <span className="mode-knob"/>
          </span>
          <span className="mode-label">
            <span className="mode-label-current">{isSimple ? 'Simple' : 'Command'}</span>
            <span className="mode-label-sub">Mode</span>
          </span>
        </button>

        <div className="top-actions">
          <button className="icon-btn" onClick={() => setAiOpen(o => !o)} title="Ask Demiurge">
            <Icon.Sparkles style={{ width: 16, height: 16 }} className={aiOpen ? 'gradient-text' : ''}/>
          </button>
          <button className="icon-btn" title="Notifications">
            <Icon.Bell style={{ width: 16, height: 16 }}/>
            <span className="dot"/>
          </button>
          <div className="avatar" title="Reza Khalili">RK</div>
        </div>
      </div>

      <div className="sidebar">
        {navSections.map(section => (
          <React.Fragment key={section.label}>
            <div className="nav-section-label">{section.label}</div>
            {section.items.map(item => {
              const I = Icon[item.icon] || Icon.Bolt;
              return (
                <div key={item.id} className={`nav-item ${page === item.id ? 'active' : ''}`} onClick={() => nav(item.id)} title={item.label}>
                  <I className="icon"/>
                  <span className="label">{item.label}</span>
                  {item.badge && (
                    <span className={`badge ${item.badge.kind || ''}`}>{item.badge.text}</span>
                  )}
                </div>
              );
            })}
          </React.Fragment>
        ))}
        <div className="workspace-switch">
          <div className="ws-mark">DX</div>
          <div className="ws-info">
            <span className="ws-name">Demiurge · ext</span>
            <span className="ws-plan">Pro · 5 seats</span>
          </div>
          <Icon.ChevronD className="ws-chevron" style={{ width: 12, height: 12 }}/>
        </div>
      </div>

      <main className="main">
        {page === 'dashboard'    && (isSimple ? <SimpleDashboard onNav={nav} settings={t}/> : <Dashboard onNav={nav} settings={t}/>)}
        {page === 'agents'       && <Agents selectedId={selectedAgent} onSelect={setSelectedAgent} onClose={() => setSelectedAgent(null)}/>}
        {page === 'workflows'    && (isSimple ? <SimpleWorkflows onSwitchMode={switchMode}/> : <Workflows/>)}
        {page === 'funnels'      && (isSimple ? <SimpleFunnels onSwitchMode={switchMode}/> : <Funnels/>)}
        {page === 'campaigns'    && (isSimple ? <SimpleCampaigns onSwitchMode={switchMode}/> : <Campaigns/>)}
        {page === 'inbox'        && (isSimple ? <SimpleInbox onSwitchMode={switchMode}/> : <Inbox/>)}
        {page === 'contacts'     && (isSimple ? <SimpleContacts onSwitchMode={switchMode}/> : <Contacts/>)}
        {page === 'persona'      && <Persona/>}
        {page === 'templates'    && <Templates/>}
        {page === 'analytics'    && (isSimple ? <SimpleAnalytics onSwitchMode={switchMode}/> : <Analytics/>)}
        {page === 'integrations' && <Integrations/>}
        {page === 'settings'     && (isSimple ? <SimpleSettings onSwitchMode={switchMode}/> : <Settings/>)}
        {page === 'calendar'     && (isSimple ? <SimpleCalendar onSwitchMode={switchMode}/> : <Calendar/>)}
        {page === 'businesses'   && <Businesses/>}
        {page === 'mission'      && <MissionControl/>}
        {page === 'channels'     && (isSimple ? <SimpleChannels onSwitchMode={switchMode}/> : <Channels/>)}
      </main>

      <div className="status-bar">
        <span className="seg ok">8 operators live</span>
        <span className="seg muted">412 in queue</span>
        <span className="seg ok">all systems normal</span>
        <span className="spacer"/>
        <span className="seg muted">v3.2.4 · build a8f12e</span>
        <span className="seg muted">GMT</span>
        <span className="seg muted">⌘K to jump anywhere</span>
      </div>

      <CommandPalette open={cmdkOpen} onClose={() => setCmdkOpen(false)} onNav={(p, id) => { nav(p, id); }}/>
      <AIPanel open={aiOpen} onClose={() => setAiOpen(false)}/>
      <ToastStack/>
      <ModalHost/>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme">
          <TweakColor
            label="Accent palette"
            value={t.palette}
            onChange={v => setTweak('palette', v)}
            options={[
              ['#4be8ff', '#8b6bff', '#ff7ad9'],
              ['#5dffb0', '#a8ff5c', '#caffea'],
              ['#ff7a3d', '#ff7ad9', '#ffb14b'],
              ['#e8eaf5', '#9aa1c0', '#5a607a'],
            ]}
          />
        </TweakSection>
        <TweakSection label="Layout">
          <TweakRadio label="Mode" value={t.mode || 'simple'} onChange={v => setTweak('mode', v)} options={['simple', 'command']}/>
          <TweakRadio label="Density" value={t.density} onChange={v => setTweak('density', v)} options={['comfortable', 'compact']}/>
          <TweakRadio label="Sidebar" value={t.sidebarStyle} onChange={v => setTweak('sidebarStyle', v)} options={['labeled', 'rail']}/>
        </TweakSection>
        <TweakSection label="Personalize">
          <TweakText label="Your name" value={t.userName} onChange={v => setTweak('userName', v)}/>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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