/* global React, ReactDOM, SEED,
   PageOverview, PageMovies, PageScheduler, PagePromotions, PageFX, PageSettings,
   ToastHost, SectionLabel */
const { useState, useEffect } = React;

const LS = 'cco-admin-demo-v3';
const loadState = () => {
  try { const s = JSON.parse(localStorage.getItem(LS) || 'null'); return s || JSON.parse(JSON.stringify(window.SEED)); }
  catch (e) { return JSON.parse(JSON.stringify(window.SEED)); }
};
const persist = (s) => {
  localStorage.setItem(LS, JSON.stringify(s));
};

const BANNER_H = 40;

// Inline stroke SVGs, 18×18 — same treatment as the real admin layout.
const Icons = {
  Overview: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="7" height="9" x="3" y="3" rx="1"/><rect width="7" height="5" x="14" y="3" rx="1"/><rect width="7" height="9" x="14" y="12" rx="1"/><rect width="7" height="5" x="3" y="16" rx="1"/></svg>,
  Matrix:   () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="7" x="3" y="3" rx="1"/><rect width="9" height="7" x="3" y="14" rx="1"/><rect width="5" height="7" x="16" y="14" rx="1"/></svg>,
  Movies:   () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M7 3v18M17 3v18M3 7h4M3 12h4M3 17h4M17 7h4M17 12h4M17 17h4"/></svg>,
  Promotions: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 12v10H4V12"/><path d="M22 7H2v5h20V7z"/><path d="M12 22V7"/><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/></svg>,
  Fx: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" x2="12" y1="2" y2="22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>,
  Settings: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.36.15.68.4.93.71.25.31.42.68.51 1.08V11a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
};

// Group names + labels match the real admin nav (subset of its 7 groups).
const NAV = [
  { group: 'Today', items: [
    { href: '#overview',   label: 'Overview',        icon: Icons.Overview },
    { href: '#scheduler',  label: 'Showtime Matrix', icon: Icons.Matrix },
  ]},
  { group: 'Catalog', items: [
    { href: '#movies',     label: 'Movies',          icon: Icons.Movies },
    { href: '#promotions', label: 'Promotions',      icon: Icons.Promotions },
  ]},
  { group: 'Cash & Books', items: [
    { href: '#fx',         label: 'FX Rates',        icon: Icons.Fx },
  ]},
  { group: 'System', items: [
    { href: '#settings',   label: 'Configuration',   icon: Icons.Settings },
  ]},
];

const PAGES = {
  overview:   PageOverview,
  movies:     PageMovies,
  scheduler:  PageScheduler,
  promotions: PagePromotions,
  fx:         PageFX,
  settings:   PageSettings,
};

function LanguageSwitcher() {
  const langs = [
    { label: 'EN', active: true },
    { label: 'عر', active: false },
    { label: 'کو', active: false },
  ];
  return (
    <div style={{display:'flex', gap: 6, padding:'12px 24px 16px', borderBottom:'1px solid var(--border-smoke)'}}>
      {langs.map(l => (
        <button
          key={l.label}
          onClick={l.active ? undefined : () => window.adminToast('The demo preview is English-only')}
          style={{
            minHeight: 32, padding:'4px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600, cursor:'pointer',
            ...(l.active
              ? {background:'var(--accent-gold)', color:'var(--surface-obsidian)', border:'1px solid var(--accent-gold)'}
              : {background:'transparent', color:'var(--text-fog)', border:'1px solid var(--border-smoke)'}),
          }}
        >{l.label}</button>
      ))}
    </div>
  );
}

function AdminShell() {
  const [state, setState] = useState(loadState);
  const [route, setRoute] = useState(() => (location.hash.slice(1) || 'overview'));

  useEffect(() => {
    const onHash = () => setRoute(location.hash.slice(1) || 'overview');
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  useEffect(() => { persist(state); }, [state]);

  const Page = PAGES[route] || PageOverview;

  const onReset = () => {
    if (!confirm('Reset all demo data to defaults?')) return;
    localStorage.removeItem(LS);
    location.reload();
  };

  const initials = state.user.nameEn.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();

  return (
    <div style={{display:'flex', minHeight:'100vh', color:'var(--text-chalk)', background:'var(--bg-void)'}}>
      {/* Demo banner */}
      <div style={{position:'fixed', top: 0, left: 0, right: 0, zIndex: 50, height: BANNER_H, background:'var(--surface-obsidian)', borderBottom:'1px solid var(--border-smoke)', padding:'0 24px', display:'flex', justifyContent:'space-between', alignItems:'center', gap: 16}}>
        <div style={{display:'flex', alignItems:'center', gap: 10, minWidth: 0}}>
          <span className="status-live" style={{background:'var(--accent-gold)'}}/>
          <span className="cos-mono" style={{color:'var(--gold-muted)'}}>
            Demo preview · seeded data · changes stay in this browser
          </span>
        </div>
        <div style={{display:'flex', gap: 8}}>
          <a href="../landing.html" className="cos-btn cos-btn-quiet" style={{fontSize: 12, padding:'4px 10px', textDecoration:'none'}}>← Back to landing</a>
          <button onClick={onReset} className="cos-btn cos-btn-quiet" style={{fontSize: 12, padding:'4px 10px'}}>Reset demo</button>
        </div>
      </div>

      {/* Sidebar — 256px, obsidian, smoke border, as in the real admin */}
      <aside style={{
        width: 256, flexShrink: 0, display:'flex', flexDirection:'column', overflowY:'auto',
        background:'var(--surface-obsidian)', borderInlineEnd:'1px solid var(--border-smoke)',
        paddingTop: BANNER_H,
      }}>
        <div style={{padding: 24, borderBottom:'1px solid var(--border-smoke)'}}>
          <div style={{display:'flex', alignItems:'center', gap: 12}}>
            <div style={{width: 34, height: 34, borderRadius: 8, background:'var(--accent-gold)', display:'grid', placeItems:'center', fontWeight: 700, fontSize: 16, letterSpacing:'-0.04em', color:'var(--surface-obsidian)'}}>CC</div>
            <div>
              <span style={{display:'block', fontSize: 14, fontWeight: 700, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--text-chalk)'}}>CinemaOS</span>
              <span className="cos-mono" style={{fontSize: 10, color:'var(--gold-muted)'}}>Central Command</span>
            </div>
          </div>
        </div>

        <LanguageSwitcher/>

        <nav style={{flex: 1, padding: 16, display:'flex', flexDirection:'column', gap: 24}}>
          {NAV.map(group => (
            <div key={group.group} style={{display:'flex', flexDirection:'column', gap: 6}}>
              <h3 className="cos-section-label" style={{padding:'0 12px', margin: 0}}>
                {group.group}
              </h3>
              <div style={{display:'flex', flexDirection:'column', gap: 2}}>
                {group.items.map(item => {
                  const isActive = '#' + route === item.href;
                  const Icon = item.icon;
                  return (
                    <a key={item.href} href={item.href} className={'cco-nav-link' + (isActive ? ' active' : '')}>
                      {isActive && <span className="cco-nav-tick"/>}
                      <Icon/>
                      <span>{item.label}</span>
                    </a>
                  );
                })}
              </div>
            </div>
          ))}
        </nav>

        <div style={{padding: 16, borderTop:'1px solid var(--border-smoke)', display:'flex', alignItems:'center', gap: 10}}>
          <div style={{width: 32, height: 32, borderRadius: 8, background:'var(--surface-raised)', border:'1px solid var(--border-smoke)', display:'grid', placeItems:'center', fontSize: 12, fontWeight: 700, color:'var(--gold-muted)'}}>{initials}</div>
          <div style={{flex: 1, minWidth: 0}}>
            <div style={{fontSize: 13, fontWeight: 500, color:'var(--text-chalk)'}}>{state.user.nameEn}</div>
            <div className="cos-mono" style={{fontSize: 10}}>{state.user.role.replace('_', ' ').toUpperCase()}</div>
          </div>
        </div>
      </aside>

      {/* Main */}
      <main style={{flex: 1, overflowY:'auto', background:'var(--bg-void)', paddingTop: BANNER_H}}>
        <div style={{padding: 32, maxWidth: 1280, margin: '0 auto'}}>
          <Page state={state} setState={setState}/>
        </div>
      </main>

      <ToastHost/>
    </div>
  );
}

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