// Main app — sidebar, top bar, page routing, tweaks panel.
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "brandColor": "#ff6b9d",
  "previewBg": "#ffffff",
  "previewFg": "#0a0a0a",
  "btnStyle": "Pill",
  "celebration": "Confetti",
  "game": "wheel",
  "consent": true,
  "ageGate": true,
  "demographics": true,
  "leadCapture": true,
  "bilingual": true,
  "sidebarMode": "expanded",
  "density": "comfy"
}/*EDITMODE-END*/;

function App() {
  const [page, setPage] = useState('home');
  const [appSwitcherOpen, setAppSwitcherOpen] = useState(false);
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  const nav = [
    { id: 'home', label: 'Home', icon: IconHome },
    { id: 'studio', label: 'Brand Studio', icon: IconPalette },
    { id: 'projects', label: 'Projects', icon: IconFolder, badge: '4' },
    { id: 'merch', label: 'My Merch', icon: IconBox },
    { id: 'insights', label: 'Insights', icon: IconChart, live: true },
  ];
  const utility = [
    { id: 'profile', label: 'Profile', icon: IconUser },
    { id: 'settings', label: 'Settings', icon: IconGear },
  ];

  const PageEl = {
    home: <HomePage tweaks={tweaks} brand={ACTIVE_BRAND} />,
    studio: <BrandStudio tweaks={tweaks} setTweak={setTweak} brand={ACTIVE_BRAND} />,
    projects: <ProjectsPage brand={ACTIVE_BRAND} />,
    merch: <MyMerchPage brand={ACTIVE_BRAND} />,
    insights: <InsightsPage />,
    profile: <ProfilePage />,
    settings: <SettingsPage />,
  }[page];

  const crumbs = {
    home: ['Home'],
    studio: ['Brand Studio', 'Joyly Summer 2026'],
    projects: ['Projects'],
    merch: ['My Merch'],
    insights: ['Insights', 'Joyly Summer 2026'],
    profile: ['Profile'],
    settings: ['Settings'],
  }[page];

  return (
    <div className="app" data-screen-label={page}>
      {/* SIDEBAR */}
      <aside className="sidebar">
        <div className="brand" onClick={() => setAppSwitcherOpen(o => !o)}>
          <div className="brand-wordmark">xotski<sup>admin</sup></div>
          <IconChev size={14} className="brand-chev" />
          {appSwitcherOpen && (
            <div className="app-switcher" onClick={e => e.stopPropagation()}>
              <button className="active"><span className="dot" /> xotski admin</button>
              <button><span className="dot purple" /> Xamplin labs</button>
              <button><span className="dot dim" /> calc.xotski.com</button>
              <div style={{ height: 1, background: 'var(--line)', margin: '6px 4px' }} />
              <button style={{ fontSize: 12, color: 'var(--text-muted)' }}>+ New workspace</button>
            </div>
          )}
        </div>

        <nav className="nav">
          {nav.map(n => {
            const Ic = n.icon;
            return (
              <div key={n.id} className={"nav-item" + (page === n.id ? ' active' : '')} onClick={() => setPage(n.id)}>
                <Ic size={17} />
                <span>{n.label}</span>
                {n.badge && <span className="badge">{n.badge}</span>}
                {n.live && <span className="live-dot" />}
              </div>
            );
          })}
        </nav>

        <div className="spacer" />

        <nav className="nav">
          {utility.map(n => {
            const Ic = n.icon;
            return (
              <div key={n.id} className={"nav-item" + (page === n.id ? ' active' : '')} onClick={() => setPage(n.id)}>
                <Ic size={17} />
                <span>{n.label}</span>
              </div>
            );
          })}
        </nav>

        <div className="brand-context">
          <div className="logo" style={{ background: ACTIVE_BRAND.logoGradient }}>{ACTIVE_BRAND.initials}</div>
          <div className="meta">
            <div className="name">{ACTIVE_BRAND.name}</div>
            <div className="role">Brand manager</div>
          </div>
          <IconChev size={14} className="swap" />
        </div>
      </aside>

      {/* MAIN */}
      <div className="main">
        <div className="topbar">
          <div className="crumb">
            {crumbs.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span className="sep">/</span>}
                <span className={i === crumbs.length - 1 ? 'here' : ''}>{c}</span>
              </React.Fragment>
            ))}
          </div>
          <div className="right">
            <div className="search" style={{ flex: 0, width: 280 }}>
              <IconSearch size={14} />
              <input placeholder="Search projects, events, contacts…" />
              <span className="mono" style={{ fontSize: 10, color: 'var(--text-muted)', padding: '1px 5px', border: '1px solid var(--line)', borderRadius: 4 }}>⌘K</span>
            </div>
            <button className="icon-btn"><IconHelp size={18} /></button>
            <button className="icon-btn" style={{ position: 'relative' }}>
              <IconBell size={18} />
              <span style={{ position: 'absolute', top: 6, right: 6, width: 7, height: 7, background: 'var(--lime)', borderRadius: '50%' }} />
            </button>
            <div className="avatar">MS</div>
          </div>
        </div>

        <div className="page">{PageEl}</div>
      </div>
    </div>
  );
}

/* ─────────────────── PROFILE + SETTINGS (light) ─────────────────── */
function ProfilePage() {
  return (
    <div style={{ maxWidth: 720 }}>
      <h1 className="page-title">Profile</h1>
      <p className="page-sub">Your account and the brands you manage.</p>
      <div className="card">
        <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
          <div className="avatar" style={{ width: 64, height: 64, fontSize: 22 }}>MS</div>
          <div>
            <div style={{ fontFamily: 'Space Grotesk', fontWeight: 600, fontSize: 20 }}>Marco Silva</div>
            <div style={{ color: 'var(--text-dim)', fontSize: 13 }}>marco@joyly.com · Brand Manager</div>
          </div>
          <button className="btn" style={{ marginLeft: 'auto' }}>Edit</button>
        </div>
        <div className="divider" />
        <div className="section-title" style={{ margin: '0 0 12px' }}>Brands</div>
        {['Joyly', 'Coast Selzer Co', 'Halo Sparkling'].map((b, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < 2 ? '1px solid var(--line)' : 0 }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: ['linear-gradient(135deg, #ff6b9d, #ffd66b)', 'linear-gradient(135deg, #6bd9ff, #4dd28b)', 'linear-gradient(135deg, #b262f5, #ff6b9d)'][i] }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600 }}>{b}</div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{i === 0 ? 'Active' : 'Member'}</div>
            </div>
            {i === 0 && <span className="pill lime">Primary</span>}
          </div>
        ))}
      </div>
    </div>
  );
}

function SettingsPage() {
  return (
    <div style={{ maxWidth: 720 }}>
      <h1 className="page-title">Settings</h1>
      <p className="page-sub">Plan, integrations, and platform-wide preferences.</p>
      <div className="card">
        <div className="card-header"><h3>Plan</h3><span className="pill lime">Growth</span></div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 18 }}>
          <div className="tier-card" style={{ padding: 16 }}>
            <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>Starter</div>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 22, fontWeight: 600, marginTop: 4 }}>$0</div>
            <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>1 project · 1 station</div>
          </div>
          <div className="tier-card featured" style={{ padding: 16 }}>
            <span className="star">Current</span>
            <div style={{ fontSize: 13, color: 'var(--lime)' }}>Growth</div>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 22, fontWeight: 600, marginTop: 4 }}>$299/mo</div>
            <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>Unlimited projects · Tier 1 games</div>
          </div>
          <div className="tier-card" style={{ padding: 16 }}>
            <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>Enterprise</div>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 22, fontWeight: 600, marginTop: 4 }}>Custom</div>
            <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>All games · CRM · SSO</div>
          </div>
        </div>
        <button className="btn primary">Upgrade to Enterprise</button>
      </div>
      <div className="card" style={{ marginTop: 14 }}>
        <div className="card-header"><h3>Integrations</h3></div>
        {[
          { n: 'Salesforce', s: 'Connected · pushes contacts hourly', on: true },
          { n: 'HubSpot', s: 'Not connected', on: false },
          { n: 'Mailchimp', s: 'Connected · adds to "Activations" list', on: true },
          { n: 'Slack', s: 'Connected · alerts to #joyly-tours', on: true },
        ].map((r, i) => (
          <div key={i} className="feature-row">
            <div>
              <div className="label">{r.n}</div>
              <div className="desc">{r.s}</div>
            </div>
            <div className="right"><div className={"toggle" + (r.on ? ' on' : '')} /></div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─────────────────── TWEAKS PANEL ─────────────────── */
function MyTweaks({ tweaks, setTweak }) {
  return (
    <window.TweaksPanel title="Tweaks">
      <window.TweakSection title="Brand">
        <window.TweakColor
          label="Brand color"
          value={tweaks.brandColor}
          onChange={v => setTweak('brandColor', v)}
          options={['#ff6b9d', '#C8E530', '#9b6bff', '#6bd9ff', '#ffd66b', '#4dd28b']}
        />
        <window.TweakRadio
          label="Preview mode"
          value={tweaks.previewBg === '#0a0a0a' ? 'dark' : 'light'}
          options={[{ label: 'Light', value: 'light' }, { label: 'Dark', value: 'dark' }]}
          onChange={v => {
            setTweak({ previewBg: v === 'dark' ? '#0a0a0a' : '#ffffff', previewFg: v === 'dark' ? '#f5f5f3' : '#0a0a0a' });
          }}
        />
      </window.TweakSection>
      <window.TweakSection title="Consumer flow">
        <window.TweakToggle label="Age gate (21+)" value={tweaks.ageGate} onChange={v => setTweak('ageGate', v)} />
        <window.TweakToggle label="Lead capture" value={tweaks.leadCapture} onChange={v => setTweak('leadCapture', v)} />
        <window.TweakToggle label="Bilingual EN/ES" value={tweaks.bilingual} onChange={v => setTweak('bilingual', v)} />
      </window.TweakSection>
      <window.TweakSection title="Game">
        <window.TweakSelect
          label="Mechanic"
          value={tweaks.game}
          options={[
            { label: 'Spin Wheel', value: 'wheel' },
            { label: 'Scratch Card', value: 'scratch' },
            { label: 'Pirinola', value: 'pirinola' },
          ]}
          onChange={v => setTweak('game', v)}
        />
        <window.TweakRadio
          label="Celebration"
          value={tweaks.celebration}
          options={[{ label: 'Confetti', value: 'Confetti' }, { label: 'Sparkles', value: 'Sparkles' }]}
          onChange={v => setTweak('celebration', v)}
        />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

function Root() {
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  // override App's local tweaks via context-free injection: pass via global
  window.__tweaks = tweaks;
  window.__setTweak = setTweak;
  return (
    <>
      <AppHosted tweaks={tweaks} setTweak={setTweak} />
      <MyTweaks tweaks={tweaks} setTweak={setTweak} />
    </>
  );
}

function AppHosted({ tweaks, setTweak }) {
  const [page, setPage] = useState('home');
  const [appSwitcherOpen, setAppSwitcherOpen] = useState(false);

  const nav = [
    { id: 'home', label: 'Home', icon: IconHome },
    { id: 'studio', label: 'Brand Studio', icon: IconPalette },
    { id: 'projects', label: 'Projects', icon: IconFolder, badge: '4' },
    { id: 'merch', label: 'My Merch', icon: IconBox },
    { id: 'insights', label: 'Insights', icon: IconChart, live: true },
  ];
  const utility = [
    { id: 'profile', label: 'Profile', icon: IconUser },
    { id: 'settings', label: 'Settings', icon: IconGear },
  ];

  const PageEl = {
    home: <HomePage tweaks={tweaks} brand={ACTIVE_BRAND} />,
    studio: <BrandStudio tweaks={tweaks} setTweak={setTweak} brand={ACTIVE_BRAND} />,
    projects: <ProjectsPage brand={ACTIVE_BRAND} />,
    merch: <MyMerchPage brand={ACTIVE_BRAND} />,
    insights: <InsightsPage />,
    profile: <ProfilePage />,
    settings: <SettingsPage />,
  }[page];

  const crumbs = {
    home: ['Home'],
    studio: ['Brand Studio', 'Joyly Summer 2026'],
    projects: ['Projects'],
    merch: ['My Merch'],
    insights: ['Insights', 'Joyly Summer 2026'],
    profile: ['Profile'],
    settings: ['Settings'],
  }[page];

  return (
    <div className="app" data-screen-label={page}>
      <aside className="sidebar">
        <div className="brand" onClick={() => setAppSwitcherOpen(o => !o)}>
          <div className="brand-wordmark">xotski<sup>admin</sup></div>
          <IconChev size={14} className="brand-chev" />
          {appSwitcherOpen && (
            <div className="app-switcher" onClick={e => e.stopPropagation()}>
              <button className="active"><span className="dot" /> xotski admin</button>
              <button><span className="dot purple" /> Xamplin labs</button>
              <button><span className="dot dim" /> calc.xotski.com</button>
              <div style={{ height: 1, background: 'var(--line)', margin: '6px 4px' }} />
              <button style={{ fontSize: 12, color: 'var(--text-muted)' }}>+ New workspace</button>
            </div>
          )}
        </div>

        <nav className="nav">
          {nav.map(n => {
            const Ic = n.icon;
            return (
              <div key={n.id} className={"nav-item" + (page === n.id ? ' active' : '')} onClick={() => setPage(n.id)}>
                <Ic size={17} />
                <span>{n.label}</span>
                {n.badge && <span className="badge">{n.badge}</span>}
                {n.live && <span className="live-dot" />}
              </div>
            );
          })}
        </nav>

        <div className="spacer" />

        <nav className="nav">
          {utility.map(n => {
            const Ic = n.icon;
            return (
              <div key={n.id} className={"nav-item" + (page === n.id ? ' active' : '')} onClick={() => setPage(n.id)}>
                <Ic size={17} />
                <span>{n.label}</span>
              </div>
            );
          })}
        </nav>

        <div className="brand-context">
          <div className="logo" style={{ background: ACTIVE_BRAND.logoGradient }}>{ACTIVE_BRAND.initials}</div>
          <div className="meta">
            <div className="name">{ACTIVE_BRAND.name}</div>
            <div className="role">Brand manager</div>
          </div>
          <IconChev size={14} className="swap" />
        </div>
      </aside>

      <div className="main">
        <div className="topbar">
          <div className="crumb">
            {crumbs.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span className="sep">/</span>}
                <span className={i === crumbs.length - 1 ? 'here' : ''}>{c}</span>
              </React.Fragment>
            ))}
          </div>
          <div className="right">
            <div className="search" style={{ flex: 0, width: 280 }}>
              <IconSearch size={14} />
              <input placeholder="Search projects, events, contacts…" />
              <span className="mono" style={{ fontSize: 10, color: 'var(--text-muted)', padding: '1px 5px', border: '1px solid var(--line)', borderRadius: 4 }}>⌘K</span>
            </div>
            <button className="icon-btn"><IconHelp size={18} /></button>
            <button className="icon-btn" style={{ position: 'relative' }}>
              <IconBell size={18} />
              <span style={{ position: 'absolute', top: 6, right: 6, width: 7, height: 7, background: 'var(--lime)', borderRadius: '50%' }} />
            </button>
            <div className="avatar">MS</div>
          </div>
        </div>

        <div className="page">{PageEl}</div>
      </div>
    </div>
  );
}

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