/* MitaOS — operator console shell.
   Sidebar grouped by the four stages, topbar with a product switcher,
   and a hash-router that swaps the eight module screens. */

const NAV = [
  { stage: 'Command',  items: [{ key: 'command', label: 'Command', icon: I.command }] },
  { stage: 'Acquire',  items: [
    { key: 'discovery', label: 'Discovery',  icon: I.discovery, mod: 'A' },
    { key: 'outreach',  label: 'Outreach',   icon: I.outreach,  mod: 'B' },
  ] },
  { stage: 'Produce',  items: [
    { key: 'briefs',    label: 'Briefs',      icon: I.briefs,    mod: 'C' },
    { key: 'qa',        label: 'Content QA',  icon: I.qa,        mod: 'D' },
  ] },
  { stage: 'Distribute', items: [
    { key: 'publishing', label: 'Publishing', icon: I.publish,   mod: 'E' },
  ] },
  { stage: 'Measure & Learn', items: [
    { key: 'performance', label: 'Performance', icon: I.perf,     mod: 'F' },
    { key: 'learning',    label: 'Learning Loop', icon: I.learning, mod: 'G' },
  ] },
  { stage: 'Reference', items: [
    { key: 'guide', label: 'Guide & glossary', dataTour: 'guide-nav',
      icon: (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z"/><path d="M9 8h6M9 12h4"/></svg>) },
  ] },
];

const SCREENS = {
  command: window.Screen_Command,
  discovery: window.Screen_Discovery,
  outreach: window.Screen_Outreach,
  briefs: window.Screen_Briefs,
  qa: window.Screen_QA,
  publishing: window.Screen_Publishing,
  performance: window.Screen_Performance,
  learning: window.Screen_Learning,
  guide: window.Screen_Guide,
};

const CRUMBS = {
  command: ['Command'], discovery: ['Acquire', 'Discovery'], outreach: ['Acquire', 'Outreach'],
  briefs: ['Produce', 'Briefs'], qa: ['Produce', 'Content QA'], publishing: ['Distribute', 'Publishing'],
  performance: ['Measure & Learn', 'Performance'], learning: ['Measure & Learn', 'Learning Loop'],
  guide: ['Reference', 'Guide & glossary'],
};

const useHashRoute = () => {
  const get = () => (window.location.hash.replace('#/', '') || 'command');
  const [route, setRoute] = React.useState(get());
  React.useEffect(() => {
    const on = () => setRoute(get());
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  const go = (k) => { window.location.hash = '#/' + k; };
  return [route, go];
};

const ProductSwitcher = ({ product, onPick }) => {
  const [open, setOpen] = React.useState(false);
  const p = MITA.products.find((x) => x.id === product) || MITA.products[0];
  const active = MITA.products.filter((x) => x.stage === 'active');
  const prospects = MITA.products.filter((x) => x.stage === 'prospect');
  const Item = (x) => (
    <button key={x.id} className={`mt-switch__item ${x.id === product ? 'is-active' : ''}`}
      onClick={() => { onPick(x.id); setOpen(false); }}>
      <Avatar initials={x.initials} gradient={x.gradient} size="sm" square />
      <span style={{ flex: 1 }}><p>{x.name}</p><p>{x.domain}</p></span>
      {x.id === product && <span style={{ color: 'var(--primary-600)' }}>{I.check}</span>}
    </button>
  );
  return (
    <div style={{ position: 'relative' }}>
      <button className="mt-switch" onClick={() => setOpen((v) => !v)} aria-expanded={open}>
        <Avatar initials={p.initials} gradient={p.gradient} size="sm" square />
        {p.name}
        <span style={{ color: 'var(--fg-subtle)', display: 'inline-flex' }}>{I.chev}</span>
      </button>
      {open && (
        <>
          <div style={{ position: 'fixed', inset: 0, zIndex: 30 }} onClick={() => setOpen(false)} />
          <div className="mt-switch__pop">
            <div className="mt-switch__group">Active · Mike's apps (Phase 1)</div>
            {active.map(Item)}
            <div className="mt-switch__group">Prospects · ICP roster (Phase 2)</div>
            {prospects.map(Item)}
          </div>
        </>
      )}
    </div>
  );
};

const Sidebar = ({ route, go }) => (
  <aside className="mt-side">
    <div className="mt-brand">
      <img src="vendor/starboard/assets/admiral-mark-color.png" alt="" />
      <div><b>MitaOS</b><span>Growth Engine OS</span></div>
    </div>
    {NAV.map((grp) => (
      <div key={grp.stage}>
        <p className="mt-stage">{grp.stage}</p>
        <nav className="mt-nav">
          {grp.items.map((it) => {
            const count = it.key === 'qa' ? MITA.queues.qa
              : it.key === 'outreach' ? MITA.queues.outreach
              : it.key === 'learning' ? MITA.queues.recs : null;
            return (
              <button key={it.key} data-tour={it.dataTour} className={`mt-nav__item ${route === it.key ? 'is-active' : ''}`} onClick={() => go(it.key)}>
                {it.icon}
                <span>{it.label}</span>
                {it.mod && <span className="mt-tag" style={{ marginLeft: 'auto', opacity: route === it.key ? 1 : 0.6 }}>{it.mod}</span>}
                {count ? <span className="mt-nav__count">{count}</span> : null}
              </button>
            );
          })}
        </nav>
      </div>
    ))}
    <div className="mt-side__foot">
      <div className="mt-userline">
        <Avatar initials="MM" gradient="g1" size="sm" />
        <div style={{ flex: 1 }}><p>Mike Mita</p><p>Founder · Growth Lead</p></div>
      </div>
    </div>
  </aside>
);

const App = () => {
  const [route, go] = useHashRoute();
  const [product, setProduct] = React.useState('P-VITAL');
  const Screen = SCREENS[route] || SCREENS.command;
  const crumbs = CRUMBS[route] || ['Command'];

  return (
    <div className="mt-app">
      <Sidebar route={route} go={go} />
      <div className="mt-main">
        <header className="mt-topbar">
          <nav className="mt-crumbs" aria-label="Breadcrumb">
            <span>MitaOS</span><span className="sep">/</span>
            {crumbs.map((c, i) => (
              <React.Fragment key={c}>
                {i > 0 && <span className="sep">/</span>}
                {i === crumbs.length - 1 ? <b>{c}</b> : <span>{c}</span>}
              </React.Fragment>
            ))}
          </nav>
          <div className="mt-topbar__spacer" />
          <div className="mt-search">
            <span style={{ width: 15, height: 15, display: 'inline-flex', color: 'var(--fg-subtle)' }}>{I.discovery}</span>
            Search creators, briefs, posts…
            <kbd>⌘K</kbd>
          </div>
          <Button variant="secondary" size="sm" leadingIcon={I.bolt} onClick={() => window.__mitaStartTour && window.__mitaStartTour()}>Guided tour</Button>
          <ProductSwitcher product={product} onPick={setProduct} />
          <Button size="sm" leadingIcon={I.plus} onClick={() => toast && toast.success('New campaign started', { description: 'Discovery is seeding a creator roster.' })}>New campaign</Button>
        </header>
        <main key={route}>
          <Screen product={product} go={go} />
        </main>
      </div>
      <Toaster position="bottom-right" />
      <TourNudge />
      <Tour />
    </div>
  );
};

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