// JFJ Affiliate Portal — App shell

const { useState: useStateApp, useEffect: useEffectApp, useMemo: useMemoApp } = React;
const { Icon, fmtMoney, Button, KPI, Card, EntityChip, StagePill, StageBar } = window;
const { useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakButton } = window;
const { Dashboard, EntityWorkspace, Quiz, Pipeline, Commissions, Leaderboard, AssetsLibrary, Announcements, LinkGen, AdminView, HQAffiliates, HQCompensation, HQContests } = window;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "pipelineView": "card",
  "role": "affiliate",
  "showOnboarding": true
}/*EDITMODE-END*/;

const ALL_NAV_ITEMS = [
  { section: 'WORKSPACE' },
  { id: 'dashboard',     label: 'Dashboard',           icon: 'Home' },
  { id: 'pipeline',      label: 'Pipeline',            icon: 'Pipeline', count: 23 },
  { id: 'commissions',   label: 'Commissions',         icon: 'Cash' },
  { id: 'leaderboard',   label: 'Leaderboard',         icon: 'Trophy', count: 3 },
  { section: 'TOOLS' },
  { id: 'assets',        label: 'Assets library',      icon: 'Folder' },
  { id: 'linkgen',       label: 'Link generator',      icon: 'Link' },
  { id: 'announcements', label: 'Announcements',       icon: 'Megaphone', count: 2 },
];

const ADMIN_NAV = [
  { section: 'HQ CONSOLE' },
  { id: 'admin',         label: 'Program overview', icon: 'Grid' },
  { id: 'hq-affiliates', label: 'Affiliates',       icon: 'Trophy' },
  { id: 'hq-comp',       label: 'Compensation',     icon: 'Cash' },
  { id: 'hq-contests',   label: 'Contests',         icon: 'Bolt' },
];

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useStateApp({ name: 'dashboard', entityId: null });
  const [showOnb, setShowOnb] = useStateApp(tweaks.showOnboarding !== false);
  const [onbStep, setOnbStep] = useStateApp(0);

  // Apply theme
  useEffectApp(() => {
    document.documentElement.setAttribute('data-theme', tweaks.theme || 'light');
  }, [tweaks.theme]);

  const nav = (name, opts) => setRoute(Object.assign({ name }, opts || {}));
  const selectEntity = (id) => setRoute({ name: 'entity', entityId: id });

  const isAdmin = tweaks.role === 'admin';

  return (
    <div className="app">
      <TopBar
        theme={tweaks.theme}
        onTheme={(v) => setTweak('theme', v)}
        role={tweaks.role}
        onRole={(v) => { setTweak('role', v); setRoute({ name: v === 'admin' ? 'admin' : 'dashboard', entityId: null }); }}
      />
      <Rail
        currentRoute={route}
        isAdmin={isAdmin}
        onNav={nav}
        onSelectEntity={selectEntity}
      />
      <main className="main" key={route.name + (route.entityId || '')}>
        {isAdmin ? (
          <>
            {(route.name === 'admin' || (!route.name.startsWith('hq-'))) && <AdminView onNav={nav} />}
            {route.name === 'hq-affiliates' && <HQAffiliates onNav={nav} />}
            {route.name === 'hq-comp' && <HQCompensation onNav={nav} />}
            {route.name === 'hq-contests' && <HQContests onNav={nav} />}
          </>
        ) : (
          <>
            {route.name === 'dashboard' && <Dashboard onNav={nav} onSelectEntity={selectEntity} />}
            {route.name === 'entity' && (
              <EntityWorkspace
                entityId={route.entityId}
                onNav={nav}
                onBack={() => nav('dashboard')}
              />
            )}
            {route.name === 'quiz' && <Quiz onExit={() => nav('entity', { entityId: window.JFJ.QUIZ.entityId })} />}
            {route.name === 'pipeline' && (
              <Pipeline
                pipelineView={tweaks.pipelineView || 'card'}
                onViewChange={(v) => setTweak('pipelineView', v)}
              />
            )}
            {route.name === 'commissions' && <Commissions />}
            {route.name === 'leaderboard' && <Leaderboard />}
            {route.name === 'assets' && <AssetsLibrary />}
            {route.name === 'linkgen' && <LinkGen />}
            {route.name === 'announcements' && <Announcements />}
          </>
        )}
      </main>

      {showOnb && tweaks.showOnboarding !== false && !isAdmin && (
        <Onboarding
          step={onbStep}
          onNext={() => setOnbStep(s => s + 1)}
          onBack={() => setOnbStep(s => Math.max(0, s - 1))}
          onClose={() => { setShowOnb(false); setTweak('showOnboarding', false); }}
        />
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Theme">
          <TweakRadio
            value={tweaks.theme}
            onChange={(v) => setTweak('theme', v)}
            options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }]}
          />
        </TweakSection>
        <TweakSection title="Role">
          <TweakRadio
            value={tweaks.role}
            onChange={(v) => { setTweak('role', v); setRoute({ name: v === 'admin' ? 'admin' : 'dashboard', entityId: null }); }}
            options={[{ value: 'affiliate', label: 'Affiliate' }, { value: 'admin', label: 'Admin / HQ' }]}
          />
        </TweakSection>
        <TweakSection title="Pipeline view">
          <TweakRadio
            value={tweaks.pipelineView}
            onChange={(v) => setTweak('pipelineView', v)}
            options={[{ value: 'card', label: 'Cards' }, { value: 'table', label: 'Table' }]}
          />
        </TweakSection>
        <TweakSection title="Onboarding">
          <TweakButton onClick={() => { setOnbStep(0); setShowOnb(true); setTweak('showOnboarding', true); }}>
            Replay onboarding
          </TweakButton>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
};

const TopBar = ({ theme, onTheme, role, onRole }) => (
  <header className="topbar">
    <div className="brand">
      <span className="brand-mark"><Icon.Logo size={22} /></span>
      <span className="brand-name">
        <span>JFJ</span>
        <span className="brand-suffix">Affiliate OS</span>
      </span>
    </div>

    <div className="topbar-search">
      <Icon.Search size={14} />
      <input placeholder="Search referrals, assets, affiliates…" />
      <kbd>⌘K</kbd>
    </div>

    <div className="topbar-spacer" />

    <div className="role-toggle">
      <button className={role === 'affiliate' ? 'active' : ''} onClick={() => onRole('affiliate')}>Affiliate</button>
      <button className={role === 'admin' ? 'active' : ''} onClick={() => onRole('admin')}>HQ</button>
    </div>

    <button className="icon-btn" title="Toggle theme" onClick={() => onTheme(theme === 'dark' ? 'light' : 'dark')}>
      {theme === 'dark' ? <Icon.Sun size={16} /> : <Icon.Moon size={16} />}
    </button>
    <button className="icon-btn" title="Notifications">
      <Icon.Bell size={16} />
    </button>

    <div className="user-chip">
      <div className="avatar">RM</div>
      <span>Ryan Mercer</span>
    </div>
  </header>
);

const Rail = ({ currentRoute, isAdmin, onNav, onSelectEntity }) => {
  const { ENTITIES, TRAINING } = window.JFJ;

  if (isAdmin) {
    return (
      <aside className="rail">
        {ADMIN_NAV.map((it, i) => {
          if (it.section) return <div key={i} className="rail-section">{it.section}</div>;
          const Ic = Icon[it.icon];
          const active = currentRoute.name === it.id || (it.id === 'admin' && !currentRoute.name.startsWith('hq-'));
          return (
            <button key={it.id + i} className={`rail-item ${active ? 'active' : ''}`} onClick={() => onNav(it.id)}>
              <span className="rail-icon"><Ic size={16} /></span>
              <span>{it.label}</span>
            </button>
          );
        })}
        <div className="rail-bottom">
          <div className="rail-cert-card">
            <div className="rail-cert-title">HQ Console</div>
            <div className="muted size-12">Manage program-wide settings, affiliates, and payouts.</div>
          </div>
        </div>
      </aside>
    );
  }

  // Find current cert in progress
  const inProgress = ENTITIES.find(e => !e.certified);
  const ipTraining = inProgress ? TRAINING[inProgress.id] : null;

  return (
    <aside className="rail">
      {ALL_NAV_ITEMS.map((it, i) => {
        if (it.section) return <div key={i} className="rail-section">{it.section}</div>;
        const Ic = Icon[it.icon];
        const active = currentRoute.name === it.id;
        return (
          <button key={it.id + i} className={`rail-item ${active ? 'active' : ''}`} onClick={() => onNav(it.id)}>
            <span className="rail-icon"><Ic size={16} /></span>
            <span>{it.label}</span>
            {it.count !== undefined && <span className="rail-count">{it.count}</span>}
          </button>
        );
      })}

      <div className="rail-section">ENTITIES</div>
      {ENTITIES.map(e => {
        const active = currentRoute.name === 'entity' && currentRoute.entityId === e.id;
        return (
          <button key={e.id} className={`rail-entity ${active ? 'active' : ''}`} onClick={() => onSelectEntity(e.id)}>
            <span className="rail-entity-dot" style={{ background: e.color }} />
            <span>{e.short}</span>
            {e.certified
              ? <span className="rail-entity-meta">✓</span>
              : <span className="rail-entity-meta">{Math.round((window.JFJ.TRAINING[e.id]?.progress || 0) * 100)}%</span>
            }
          </button>
        );
      })}

      <div className="rail-bottom">
        {inProgress && ipTraining && ipTraining.progress < 1 ? (
          <div className="rail-cert-card">
            <div className="rail-cert-title">Finish {inProgress.short} cert</div>
            <div className="rail-cert-bar"><div style={{ width: `${ipTraining.progress * 100}%` }} /></div>
            <div className="rail-cert-meta">{Math.round(ipTraining.progress * 100)}% · unlocks your link</div>
            <Button variant="primary" size="sm" full onClick={() => onSelectEntity(inProgress.id)}>Resume</Button>
          </div>
        ) : (
          <div className="rail-cert-card">
            <div className="rail-cert-title">Got a question?</div>
            <div className="muted size-12">Office hours every Thursday, 2pm CT.</div>
          </div>
        )}
      </div>
    </aside>
  );
};

// ============== ONBOARDING ==============
const Onboarding = ({ step, onNext, onBack, onClose }) => {
  const STEPS = [
    {
      title: 'Welcome to JFJ Affiliate OS, Ryan.',
      body: "One portal, every JFJ offer. You'll get certified, grab your link, and track every referral end-to-end — no more juggling logins or guessing where a deal stands.",
      cta: 'Take the tour',
    },
    {
      title: 'Four entities. One pipeline.',
      body: "Trusts. Tax Strategy. Consulting. Lead Gen. Each has its own offer, training, and payout structure — but you see everything in one master pipeline. Filter, toggle, color-coded.",
      cta: 'Got it',
    },
    {
      title: 'Get certified, get paid.',
      body: "Each entity requires a quick training + quiz before you can promote it. Trusts and Tax are already done. Consulting and Lead Gen are waiting — should take ~45 min combined.",
      cta: 'Show me my training',
    },
    {
      title: 'You\'re in a contest.',
      body: "May Trust Blitz: $5k + a Vegas trip for whoever closes the most Trust deals this month. You're #4 right now. Three more closes and you're on the podium.",
      cta: "Let's go",
    },
  ];
  const total = STEPS.length;
  const cur = STEPS[step];
  const last = step === total - 1;

  return (
    <div className="onb" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="onb-card">
        <div className="onb-step-dots">
          {STEPS.map((_, i) => <div key={i} className={i <= step ? 'active' : ''} />)}
        </div>
        <div className="muted size-12 mono mb-8">STEP {step + 1} OF {total}</div>
        <h2>{cur.title}</h2>
        <p>{cur.body}</p>
        <div className="onb-actions">
          {step > 0 && <Button variant="ghost" onClick={onBack}>Back</Button>}
          <Button variant="ghost" onClick={onClose}>Skip</Button>
          <Button variant="primary" onClick={last ? onClose : onNext} trailing={!last && <Icon.Chevron size={14} />}>
            {cur.cta}
          </Button>
        </div>
      </div>
    </div>
  );
};

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