// CAP Demo Dashboard — client-only build forked from RCG.
//
// What's different from RCG:
//   - Single "CAP Team sign in" button (no Team/Client tabs)
//   - No "View as" entity switcher
//   - No Internal Tools sidebar section
//   - No RCG self-entity, no isSelf paths
//   - All mock data (Pages Functions removed)
//   - 3-screen onboarding flow runs on first visit

const { useState: auState, useEffect: auEffect, useMemo: auMemo, useRef: auRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentMode": "red",
  "showSparklines": true,
  "density": "comfortable",
  "wordmark": "CAP"
}/*EDITMODE-END*/;

// Tabs visible to CAP. Membership is first so it's the landing view.
const CAP_TABS = [
  { id: 'membership', label: 'Membership', icon: 'Users' },
  { id: 'overview', label: 'Overview', icon: 'LayoutDashboard' },
  { id: 'paid', label: 'Paid Media', icon: 'Target' },
  { id: 'email', label: 'Email', icon: 'Mail' },
  { id: 'web', label: 'Website & SEO', icon: 'Globe' },
  { id: 'crm', label: 'CRM Pipeline', icon: 'GitBranch' },
  { id: 'report', label: 'Monthly Report', icon: 'FileText' },
];
const CAP_TAB_IDS = new Set(CAP_TABS.map((t) => t.id));

const ONBOARDING_DONE_KEY = 'cap_onboarding_done_v1';

function useToasts() {
  const [toasts, setToasts] = auState([]);
  const idRef = auRef(0);
  function push(msg, kind) {
    const id = ++idRef.current;
    setToasts((t) => [...t, { id, msg, kind }]);
    setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 3000);
  }
  return [toasts, push];
}

// ── SIGN-IN SCREEN ──────────────────────────────────────
// Single-button sign in. The demo doesn't validate credentials; this is
// purely to set the "you've arrived" tone before onboarding kicks in.
function SignInScreen({ onSignIn }) {
  return (
    <div className="login-wrap">
      <div className="login-card" style={{ textAlign: 'center' }}>
        <div className="login-mark" style={{ justifyContent: 'center', marginBottom: 24 }}>
          <img src="assets/logo-small-box-black.png" alt="" style={{ width: 36, height: 36, display: 'block' }} />
        </div>

        <h1 className="login-title">
          The <span style={{ color: 'var(--brand-red)', fontStyle: 'italic', textTransform: 'none' }}>CAP</span> dashboard
        </h1>
        <p className="login-sub" style={{ marginBottom: 28 }}>
          A private preview built by Rottman Creative.<br/>
          Tap below to walk through it.
        </p>

        <Pill type="button" variant="filled" style={{ width: '100%', minHeight: 48, fontSize: 12 }}
          onClick={onSignIn}>
          CAP Team — Sign in
        </Pill>

        <div className="login-footer" style={{ justifyContent: 'center', marginTop: 28 }}>
          <span style={{ fontSize: 11, color: 'var(--ink-stone)' }}>
            © 2026 Rottman Creative Group · Built for CAP
          </span>
        </div>
      </div>
    </div>
  );
}

// ── HEADER (slim, no entity switcher, no Connect Sources) ──
// Connect Sources lives in the onboarding flow on this demo build — having
// a topbar shortcut for it is redundant. Replay onboarding from the avatar
// menu if you want to revisit the connection flow.
function CapTopbar({ user, onReplayOnboarding, onSignOut, tabId }) {
  const tab = CAP_TABS.find((t) => t.id === tabId);
  return (
    <header className="topbar">
      <div className="topbar-title">
        <span className="crumb">College of American Pathologists · </span>
        {tab?.label || ''}
      </div>
      <div className="topbar-actions">
        <Dropdown trigger={<div className="avatar">{user.name.split(' ').map((s) => s[0]).slice(0, 2).join('')}</div>}>
          <div className="dd-section">{user.name}</div>
          <div style={{ padding: '0 14px 8px', fontSize: 11.5, color: 'var(--ink-stone)' }}>{user.email}</div>
          <div className="dd-rule" />
          <button className="dd-item" onClick={onReplayOnboarding}><Icon name="RefreshCw" size={14} /> Replay onboarding</button>
          <button className="dd-item"><Icon name="Settings" size={14} /> Settings</button>
          <div className="dd-rule" />
          <button className="dd-item" onClick={onSignOut}><Icon name="LogOut" size={14} /> Sign out</button>
        </Dropdown>
      </div>
    </header>
  );
}

// ── SIDEBAR (client-only — no Internal Tools, no View-as) ──
function CapSidebar({ currentEntity, tabId, onSelectTab, wordmark }) {
  return (
    <aside className="sidebar">
      <div className="sidebar-head">
        <div className="sidebar-mark">
          <img src="assets/logo-small-box-black.png" alt="" />
        </div>
        <span className="sidebar-wordmark">{wordmark}</span>
      </div>

      <div className="sidebar-scroll">
        <div className="sidebar-entity">
          <p className="sidebar-entity-eyebrow">Your account</p>
          <h2 className="sidebar-entity-name">{currentEntity.name}</h2>
          <div className="sidebar-entity-meta">{currentEntity.industry}</div>
        </div>

        <div className="sidebar-section">
          <div className="sidebar-section-label">Dashboard</div>
          {CAP_TABS.map((t) => (
            <button
              key={t.id}
              className={`sidebar-item ${tabId === t.id ? 'active' : ''}`}
              onClick={() => onSelectTab(t.id)}
            >
              <Icon name={t.icon} size={14} /> {t.label}
            </button>
          ))}
        </div>
      </div>
    </aside>
  );
}

// ── DASHBOARD ROOT ───────────────────────────────────────
function CapDashboard({ user, onSignOut, onReplayOnboarding, tweaks, setTweak, pushToast }) {
  const [tabId, setTabId] = auState('membership');
  const currentEntity = window.RCG_CLIENTS.find((c) => c.id === 'cap') || window.RCG_CLIENTS[0];

  function selectTab(nextTabId) {
    if (!CAP_TAB_IDS.has(nextTabId)) return;
    setTabId(nextTabId);
  }

  // OverviewTab takes an onConnect prop — point it at the onboarding replay
  // so "Connect a source" from inside the page hits the same flow Clemmie
  // saw on her first visit.
  function openOnboarding() { onReplayOnboarding(); }

  function renderTab() {
    switch (tabId) {
      case 'membership': return <MembershipTab client={currentEntity} />;
      case 'overview':   return <OverviewTab client={currentEntity} onConnect={openOnboarding} />;
      case 'paid':       return <PaidTab client={currentEntity} />;
      case 'email':      return <EmailTab client={currentEntity} />;
      case 'web':        return <WebSeoTab client={currentEntity} />;
      case 'crm':        return <CrmTab client={currentEntity} />;
      case 'report':     return <MonthlyReportTab client={currentEntity} pushToast={pushToast} />;
      default:           return null;
    }
  }

  return (
    <div className="app-layout">
      <CapSidebar
        currentEntity={currentEntity}
        tabId={tabId}
        onSelectTab={selectTab}
        wordmark={tweaks.wordmark || 'CAP'}
      />

      <div className="app-main">
        <CapTopbar
          user={user}
          tabId={tabId}
          onReplayOnboarding={onReplayOnboarding}
          onSignOut={onSignOut}
        />

        <div className="page-wrap" key={tabId}>
          {renderTab()}
        </div>
      </div>
    </div>
  );
}

// ── ROOT APP ─────────────────────────────────────────────
function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [user, setUser] = auState(null);
  const [onboardingDone, setOnboardingDone] = auState(() => {
    try { return localStorage.getItem(ONBOARDING_DONE_KEY) === '1'; } catch { return false; }
  });
  const [toasts, pushToast] = useToasts();

  function signIn() {
    setUser({ type: 'client', name: 'Clemmie Lozano', email: 'clemmie.lozano@cap.org', clientId: 'cap' });
  }

  function signOut() {
    setUser(null);
  }

  function finishOnboarding() {
    try { localStorage.setItem(ONBOARDING_DONE_KEY, '1'); } catch {}
    setOnboardingDone(true);
  }

  function replayOnboarding() {
    try { localStorage.removeItem(ONBOARDING_DONE_KEY); } catch {}
    setOnboardingDone(false);
  }

  auEffect(() => {
    const root = document.documentElement;
    if (tweaks.density === 'compact') {
      root.style.setProperty('--card-pad', '20px');
    } else {
      root.style.removeProperty('--card-pad');
    }
  }, [tweaks.density]);

  let body;
  if (!user) {
    body = <SignInScreen onSignIn={signIn} />;
  } else if (!onboardingDone) {
    body = <CapOnboarding user={user} onComplete={finishOnboarding} pushToast={pushToast} />;
  } else {
    body = <CapDashboard
      user={user}
      onSignOut={signOut}
      onReplayOnboarding={replayOnboarding}
      tweaks={tweaks}
      setTweak={setTweak}
      pushToast={pushToast}
    />;
  }

  return (
    <React.Fragment>
      {body}
      <Toast toasts={toasts} />
    </React.Fragment>
  );
}

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