// Pathway app shell
const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA } = React;

const NAV = [
  { group: 'ANALYTICS', items: [
    { id: 'overview', label: 'Overview', icon: 'home' },
    { id: 'channels', label: 'Channels', icon: 'channels' },
    { id: 'locations', label: 'Locations', icon: 'venues' },
    { id: 'bookings', label: 'Bookings Activity', icon: 'calendar' },
    { id: 'guests', label: 'Guest Insights', icon: 'audience' },
  ]},
  { group: 'OPERATIONS', items: [
    { id: 'reports', label: 'Reports', icon: 'reports' },
    { id: 'settings', label: 'Settings', icon: 'settings' },
  ]},
];

const PAGE_TITLES = {
  overview: ['Overview', 'At-a-glance performance across the group'],
  channels: ['Channels', 'Performance by media channel'],
  channel: ['Channel', 'Channel detail'],
  reports: ['Reports', 'Scheduled exports and boardroom-ready summaries'],
  settings: ['Settings', 'Integrations and RAM configuration'],
  locations: ['Location Performance', 'Track revenue attribution across your venue portfolio'],
  guests: ['Guest Insights', 'Behaviour and intelligence from SevenRooms data'],
  bookings: ['Bookings Activity', 'Every booking, attributed — from first click to POS match'],
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "cream",
  "overviewVariant": "A"
}/*EDITMODE-END*/;

function loadState() {
  try {
    const s = JSON.parse(localStorage.getItem('coverstory:v1') || '{}');
    return s;
  } catch { return {}; }
}
function saveState(s) {
  localStorage.setItem('coverstory:v1', JSON.stringify(s));
}

function App() {
  const saved = loadState();
  const [route, setRoute] = useStateA(saved.route || 'overview');
  const [param, setParam] = useStateA(saved.param || null);
  const [range, setRange] = useStateA(saved.range || '30d');
  const [scenario, setScenario] = useStateA('Actual');
  const [channelsOn, setChannelsOn] = useStateA(saved.channelsOn || Object.fromEntries(CoverStory.CHANNELS.map(c => [c.id, true])));
  const [theme, setTheme] = useStateA(saved.theme || TWEAK_DEFAULTS.theme);
  const [overviewVariant, setOverviewVariant] = useStateA(saved.overviewVariant || TWEAK_DEFAULTS.overviewVariant);
  const [tweaksOpen, setTweaksOpen] = useStateA(false);
  const [exportToast, setExportToast] = useStateA(null);
  // Bumped when live data arrives, forcing a re-render of the whole tree.
  const [dataVersion, setDataVersion] = useStateA(0);

  useEffectA(() => { document.body.setAttribute('data-theme', theme); }, [theme]);
  useEffectA(() => { saveState({ route, param, range, channelsOn, theme, overviewVariant }); }, [route, param, range, channelsOn, theme, overviewVariant]);

  // When the user changes the date range, ask the data layer to re-point
  // LOCATIONS / CHANNEL_MIX at that range's prefetched bundle. Then bump
  // dataVersion so the tree re-renders with the new numbers.
  useEffectA(() => {
    if (CoverStory.setCurrentRange) {
      const switched = CoverStory.setCurrentRange(range);
      if (switched) setDataVersion(v => v + 1);
    }
  }, [range]);

  // The data layer dispatches this once the API returns. Merge state with the
  // new channel taxonomy: keep the user's existing on/off choices, default
  // any NEWLY-DISCOVERED channels (e.g. a new source like chatgpt that
  // didn't exist last session) to ON so they surface immediately, and prune
  // ids that no longer appear in the live data. This prevents stale demo
  // channels from rendering empty rows in the donut/chip strip.
  useEffectA(() => {
    function onReady() {
      setChannelsOn(prev => {
        const merged = { ...prev };
        CoverStory.CHANNELS.forEach(c => {
          if (!(c.id in merged)) merged[c.id] = true;
        });
        const liveIds = new Set(CoverStory.CHANNELS.map(c => c.id));
        Object.keys(merged).forEach(id => { if (!liveIds.has(id)) delete merged[id]; });
        return merged;
      });
      setDataVersion(v => v + 1);
    }
    window.addEventListener('coverstory:data-ready', onReady);
    return () => window.removeEventListener('coverstory:data-ready', onReady);
  }, []);

  // Tweaks protocol — disabled in production. The cream/dark/light-purple +
  // OverviewA/B picker was an internal demo affordance; we keep the panel
  // code in case we re-enable behind a feature flag, but the postMessage
  // listener that opens it is gone, so no chance of accidental reveal during
  // a client demo.

  function go(r, p) { setRoute(r); setParam(p?.id || null); window.scrollTo(0, 0); }
  function toggleChannel(id) {
    setChannelsOn(prev => ({ ...prev, [id]: !prev[id] }));
  }

  const rangeLabel = CoverStory.RANGES[range].label;
  const ctx = { range, rangeLabel, channelsOn, scenario, go, route, param };

  const [title, sub] = PAGE_TITLES[route] || ['', ''];

  function handleExport() {
    setExportToast('Export queued — sent to you@demo-restaurant-group.com');
    setTimeout(() => setExportToast(null), 2800);
  }

  function persistTweak(patch) {
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*'); } catch {}
  }

  return (
    <div className="pw-app">
      {/* Sidebar */}
      <aside className="pw-sidebar">
        <div className="pw-logo">
          <div className="pw-logo-mark"><Sparkle size="14" /></div>
          <div>
            <div className="pw-logo-word">CoverStory</div>
            <div className="pw-logo-sub">by NovaStory</div>
          </div>
        </div>
        <nav className="pw-nav">
          {NAV.map(g => (
            <div key={g.group}>
              <div className="pw-nav-group-label">{g.group}</div>
              {g.items.map(it => {
                const IconC = Icon[it.icon];
                const active = route === it.id || (it.id === 'channels' && route === 'channel');
                return (
                  <a key={it.id} href="#" className={active ? 'active' : ''}
                     onClick={e => { e.preventDefault(); go(it.id); }}>
                    <IconC /> {it.label}
                  </a>
                );
              })}
            </div>
          ))}
        </nav>
        <div className="pw-sidebar-footer">
          <div className="pw-avatar">M</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Mildreds Group</div>
            <div style={{ fontSize: 11, color: 'var(--pw-fg-subtle)' }}>5 venues · Marketing</div>
          </div>
        </div>
      </aside>

      {/* Main */}
      <main className="pw-main">
        {/* Topbar */}
        <div className="pw-topbar">
          <div className="pw-crumbs">
            <span>Analytics</span>
            <Icon.chevron width="12" height="12" style={{ transform: 'rotate(-90deg)' }} />
            <span className="cur">{title}</span>
          </div>
          <div className="pw-topbar-actions">
            <DateRange value={range} onChange={setRange} />
            <button className="pw-btn" onClick={handleExport}><Icon.download /> Export</button>
            <button className="pw-btn pw-btn-primary"><Sparkle size="12" color="currentColor" /> Share</button>
          </div>
        </div>

        {/* Page head + content */}
        <div className="pw-content">
          <div className="pw-page-head">
            <div>
              <div className="pw-eyebrow">CoverStory <span style={{ margin: '0 6px', color: 'var(--pw-fg-subtle)' }}>/</span> {title}</div>
              <h1 className="pw-page-title">{title}</h1>
              <div className="pw-page-sub">{sub}</div>
            </div>
            {(route === 'overview' || route === 'channels') && (
              <div style={{ maxWidth: 620 }}>
                <ChannelFilters channelsOn={channelsOn} onToggle={toggleChannel} />
              </div>
            )}
          </div>

          {route === 'overview' && <OverviewPage ctx={ctx} variant={overviewVariant} />}
          {route === 'channels' && <ChannelsPage ctx={ctx} />}
          {route === 'channel'  && <ChannelDetailPage ctx={ctx} />}
          {route === 'locations'&& <LocationsPage ctx={ctx} />}
          {route === 'location' && <LocationDetailPage ctx={ctx} />}
          {route === 'bookings' && <BookingsActivityPage ctx={ctx} />}
          {route === 'guests'   && <GuestInsightsPage ctx={ctx} />}
          {route === 'reports'  && <ReportsPage ctx={ctx} />}
          {route === 'settings' && <SettingsPage ctx={ctx} />}
        </div>
      </main>

      {/* Export toast */}
      {exportToast && (
        <div style={{ position: 'fixed', bottom: 24, left: 260, background: 'var(--pw-fg)', color: 'var(--pw-bg)', padding: '12px 18px', fontSize: 13, fontWeight: 500, zIndex: 200 }}>
          {exportToast}
        </div>
      )}

      {/* Tweaks panel */}
      {tweaksOpen && (
        <div className="pw-tweaks">
          <div className="pw-tweaks-title">Tweaks</div>

          <div style={{ fontSize: 11, color: 'var(--pw-fg-muted)', marginBottom: 6 }}>Colourway</div>
          <div className="pw-tweaks-row" style={{ marginBottom: 14 }}>
            {[
              { id: 'cream', bg: '#FDFAF0', fg: '#3A2839' },
              { id: 'dark', bg: '#2B1D2B', fg: '#C5B8FF' },
              { id: 'light-purple', bg: '#EDE7FF', fg: '#3A2839' },
            ].map(t => (
              <div key={t.id}
                className={'pw-tweaks-swatch' + (theme === t.id ? ' on' : '')}
                style={{ background: t.bg }}
                onClick={() => { setTheme(t.id); persistTweak({ theme: t.id }); }}>
                <div style={{ position: 'absolute', inset: 4, background: t.fg, width: 6, height: 6 }}></div>
              </div>
            ))}
          </div>

          <div style={{ fontSize: 11, color: 'var(--pw-fg-muted)', marginBottom: 6 }}>Overview layout</div>
          <div className="pw-tweaks-row">
            {['A', 'B'].map(v => (
              <button key={v} className="pw-btn" style={{ flex: 1, justifyContent: 'center',
                background: overviewVariant === v ? 'var(--pw-accent)' : 'var(--pw-surface)',
                color: overviewVariant === v ? 'var(--pw-accent-fg)' : 'var(--pw-fg)' }}
                onClick={() => { setOverviewVariant(v); persistTweak({ overviewVariant: v }); }}>
                {v === 'A' ? 'Grid' : 'Hero'}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

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