// Screenshot-backed module mocks — REAL iPad walkthrough captures.
// Loaded AFTER tour-mocks.jsx so it overrides the entries in window.MockByKey.
// Old synthetic mocks are preserved on window.MockByKey_synthetic.
//
// All captures are landscape iPad (2752×2196, banner cropped) living in
// assets/screens/wt/NNN.jpg. Frame is tablet + landscape for every module.
//
// Coverage map (wt file → tab). Tabs with no dedicated capture reuse the
// closest relative and are marked (reuse):
//   home       → 001
//   dashboard  → 002
//   match      → fixtures 004 · post-match 007 · scorebook 032
//   scorebook  → innings 037 · stats 051 · insights 057 · pulse 038 · flip 043 ·
//                crestsmart/commentary/fan 037 (reuse live view — no dedicated capture)
//   roster     → MOBILE (portrait) from clip 03 — all 7 tabs
//                (mr-overview / profile / career / batting / bowling / fielding / awards)
//   squads     → dna 013 · gallery 016 · training 017 ·
//                teams/museum 016 (reuse — no dedicated capture)
//   intel      → strategy 022 · perf 024 · attrs 025 · venue 028 ·
//                opp 029 · captains 030 · h2h 022 (reuse — no dedicated capture)
//   stats      → batting 020 · records 021 ·
//                bowling/all-rnd/explorer 020 (reuse leaderboard — no dedicated capture)
//   settings & broadcast — still synthetic (partial captures only)

const { useState: rmUseState, useEffect: rmUseEffect } = React;

const WT = (n) => `assets/screens/wt/${n}.jpg`;

// ── Helper: report a tab id to the explainer panel.
function useTabReport(onTabChange, tabId) {
  rmUseEffect(() => { if (onTabChange && tabId) onTabChange(tabId); }, [onTabChange, tabId]);
}

// ── <ScreenShot> — the mock body. iPad-shaped image + optional tab strip.
function ScreenShot({ src, alt = '', landscape = false, tabs, activeTab, onTab, frame = 'phone' }) {
  const [ar, setAr] = rmUseState(landscape ? '3 / 2' : '9 / 19.5');

  const hasTabs = tabs && tabs.length > 1;
  const [visited, setVisited] = rmUseState(() => new Set(activeTab ? [activeTab] : []));
  rmUseEffect(() => {
    if (activeTab) setVisited(prev => prev.has(activeTab) ? prev : new Set(prev).add(activeTab));
  }, [activeTab]);
  const allSeen = hasTabs && visited.size >= tabs.length;
  const seenCount = hasTabs ? visited.size : 0;
  const nextTab = hasTabs && !allSeen
    ? (tabs.find(t => !visited.has(t.id)) || null)
    : null;

  return (
    <div
      className={`scrn ${landscape ? 'scrn-land' : 'scrn-port'} scrn-frame-${frame}`}
      style={{ '--shot-ar': ar }}
    >
      <div className="scrn-device">
        <div className="scrn-bezel">
          <img
            src={src}
            alt={alt}
            className="scrn-img"
            draggable={false}
            onLoad={(e) => {
              const w = e.target.naturalWidth, h = e.target.naturalHeight;
              if (w && h) setAr(`${w} / ${h}`);
            }}
          />
        </div>
      </div>
      {hasTabs && (
        <div className="scrn-explore">
          <div className={`scrn-cue ${allSeen ? 'done' : ''}`} aria-live="polite">
            {allSeen
              ? <span className="scrn-cue-label"><span className="scrn-cue-check">✓</span> All {tabs.length} explored — nice</span>
              : <span className="scrn-cue-label">Tap each tab to see what it does</span>}
            <span className="scrn-cue-count">{seenCount}<span className="scrn-cue-slash">/</span>{tabs.length}</span>
          </div>
          <div className="scrn-progress" aria-hidden="true">
            <span className="scrn-progress-fill" style={{ width: `${(seenCount / tabs.length) * 100}%` }}></span>
          </div>
          <div className="scrn-tabs" role="tablist">
            {tabs.map(t => {
              const isActive = activeTab === t.id;
              const seen = visited.has(t.id);
              const isNext = nextTab && t.id === nextTab.id;
              return (
                <button
                  key={t.id}
                  role="tab"
                  aria-selected={isActive}
                  className={`scrn-tab ${isActive ? 'active' : ''} ${seen ? 'seen' : 'unseen'} ${isNext ? 'next' : ''}`}
                  onClick={(e) => { e.stopPropagation(); onTab && onTab(t.id); }}
                >
                  {isNext && <span className="scrn-tab-pointer" aria-hidden="true"></span>}
                  <span className="scrn-tab-mark">{seen && !isActive ? '✓' : '+'}</span>
                  {t.label}
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

// Small helper for the tabbed modules — keeps each mock tiny.
// Defaults to a landscape tablet frame; pass frame="phone" landscape={false}
// for the mobile (portrait) modules.
function TabbedShot({ tabs, alt, onTabChange, frame = 'tablet', landscape = true }) {
  const [active, setActive] = rmUseState(tabs[0].id);
  useTabReport(onTabChange, active);
  const cur = tabs.find(t => t.id === active) || tabs[0];
  return (
    <ScreenShot
      src={cur.src}
      alt={alt}
      tabs={tabs}
      activeTab={active}
      onTab={setActive}
      landscape={landscape}
      frame={frame}
    />
  );
}

// ─── 1. HOME ────────────────────────────────────────────────────────────────
function MockHomeShot({ onTabChange }) {
  useTabReport(onTabChange, 'home');
  return <ScreenShot src={WT('001')} alt="CREST Home screen" landscape frame="tablet" />;
}

// ─── 2. THE DUGOUT (Dashboard) ─────────────────────────────────────────────
function MockDugoutShot({ onTabChange }) {
  useTabReport(onTabChange, 'dugout');
  return <ScreenShot src={WT('002')} alt="The Dugout dashboard" landscape frame="tablet" />;
}

// ─── 3. MATCH CENTER ────────────────────────────────────────────────────────
function MockMatchShot({ onTabChange }) {
  return <TabbedShot onTabChange={onTabChange} alt="Match Center" tabs={[
    { id: 'fixtures',   label: 'FIXTURES',           src: WT('004') },
    { id: 'post-match', label: 'POST-MATCH SCORING', src: WT('postmatch') },
    { id: 'scorebook',  label: 'SCOREBOOK',          src: WT('032') },
  ]} />;
}

// ─── 3.5 SCOREBOOK (deep dive) ──────────────────────────────────────────────
function MockScorebookShot({ onTabChange }) {
  return <TabbedShot onTabChange={onTabChange} alt="Live Scorebook" tabs={[
    { id: 'innings',    label: 'INNINGS',    src: WT('037') },
    { id: 'matchstats', label: 'STATS',      src: WT('051') },
    { id: 'insights',   label: 'INSIGHTS',   src: WT('057') },
    { id: 'pulse',      label: 'CRESTPULSE', src: WT('pulse') },
  ]} />;
}

// ─── 4. ROSTER (mobile — clip 03 covers all 7 tabs cleanly) ─────────────────
function MockRosterShot({ onTabChange }) {
  return <TabbedShot onTabChange={onTabChange} alt="Roster · Player Profile" frame="phone" landscape={false} tabs={[
    { id: 'overview', label: 'OVERVIEW', src: WT('mr-overview') },
    { id: 'profile',  label: 'PROFILE',  src: WT('mr-profile') },
    { id: 'career',   label: 'CAREER',   src: WT('mr-career') },
    { id: 'batting',  label: 'BATTING',  src: WT('mr-batting') },
    { id: 'bowling',  label: 'BOWLING',  src: WT('mr-bowling') },
    { id: 'fielding', label: 'FIELDING', src: WT('mr-fielding') },
    { id: 'awards',   label: 'AWARDS',   src: WT('mr-awards') },
  ]} />;
}

// ─── 5. SQUADS ──────────────────────────────────────────────────────────────
function MockSquadsShot({ onTabChange }) {
  return <TabbedShot onTabChange={onTabChange} alt="Squads" tabs={[
    { id: 'dna',      label: 'SQUAD DNA',    src: WT('013') },
    { id: 'gallery',  label: 'TEAM GALLERY', src: WT('016') },
    { id: 'training', label: 'TRAINING',     src: WT('017') },
  ]} />;
}

// ─── 6. INTELLIGENCE HUB ───────────────────────────────────────────────────
function MockIntelShot({ onTabChange }) {
  return <TabbedShot onTabChange={onTabChange} alt="Intelligence Hub" tabs={[
    { id: 'strategy', label: 'STRATEGY',    src: WT('022') },
    { id: 'perf',     label: 'PERFORMANCE', src: WT('024') },
    { id: 'attrs',    label: 'ATTRIBUTES',  src: WT('attrs') },
    { id: 'venue',    label: 'VENUE',       src: WT('028') },
    { id: 'opp',      label: 'OPPONENT',    src: WT('029') },
  ]} />;
}

// ─── 7. STATISTICS ─────────────────────────────────────────────────────────
function MockStatsShot({ onTabChange }) {
  return <TabbedShot onTabChange={onTabChange} alt="Statistics" tabs={[
    { id: 'batting',  label: 'BATTING', src: WT('020') },
    { id: 'records',  label: 'RECORDS', src: WT('021') },
  ]} />;
}

// ─── 8. SETTINGS ──────────────────────────────────────────────────────
// Only one Settings capture exists (031 = Appearance / Themes). appear gets it;
// the other tabs reuse it until per-tab captures are available.
// Only the Appearance/Themes tab was ever captured (031). Rather than show 7
// tabs that all display the same screen, render a single representative shot;
// the per-tab detail lives in the explainer text (appear).
function MockSettingsShot({ onTabChange }) {
  useTabReport(onTabChange, 'appear');
  return <ScreenShot src={WT('031')} alt="Settings · Appearance" landscape frame="tablet" />;
}

// ─── 8.5 BROADCAST KIT (deep dive — Flex Cards) ─────────────────────────
// Winner (041) and POTM (042) map exactly; the remaining tabs reuse the other
// real Flex Cards (043 batting, 044 bowling, 045 match result) as stand-ins
// until dedicated Assets / Fixture / Lineup captures are available.
function MockBroadcastShot({ onTabChange }) {
  return <TabbedShot onTabChange={onTabChange} alt="Broadcast Kit" tabs={[
    { id: 'winner',  label: 'WINNER', src: WT('041') },
    { id: 'potm',    label: 'POTM',   src: WT('042') },
  ]} />;
}

// ─── Override MockByKey with screenshot versions ───────────────────────────
window.MockByKey_synthetic = { ...window.MockByKey };
Object.assign(window.MockByKey, {
  home:      MockHomeShot,
  dashboard: MockDugoutShot,
  match:     MockMatchShot,
  scorebook: MockScorebookShot,
  roster:    MockRosterShot,
  squads:    MockSquadsShot,
  intel:     MockIntelShot,
  stats:     MockStatsShot,
  settings:  MockSettingsShot,
  broadcast: MockBroadcastShot,
});

// Every walkthrough capture is landscape iPad — all screenshot modules
// want the landscape stage.
// Roster is now a portrait mobile module, so it is intentionally NOT landscape.
window.LANDSCAPE_MODULES = new Set(['home', 'dashboard', 'match', 'scorebook', 'squads', 'intel', 'stats', 'settings', 'broadcast']);

// Modules that render a single screenshot with NO tab rail. The card layout
// skips the rail gutter for these so the tablet centres full-width.
window.NOTAB_MODULES = new Set(['home', 'dashboard', 'settings']);
