// homehub-app.jsx — Mounts the Home Hub design canvas + Tweaks panel.

const { useState: hhUseState, useEffect: hhUseEffect, useMemo: hhUseMemo, useRef: hhUseRef } = React;

// Mobile phone frame for artboards
function HHPhone({ w = 420, h = 920, children }) {
  return (
    <div className="hh-phone" style={{ width: w, height: h }}>
      <div className="hh-phone-inner">{children}</div>
    </div>
  );
}

const HH_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "locale": "fa",
  "avatarSide": "start",
  "fiveTabs": false,
  "scrollAware": true,
  "dateMode": "hybrid",
  "notifSimulate": true,
  "showEmpty": false
}/*EDITMODE-END*/;

function HHApp() {
  const [t, setTweak] = useTweaks(HH_TWEAK_DEFAULTS);
  const [modalItem, setModalItem] = hhUseState(null);
  const [predicted, setPredicted] = hhUseState(null);  // local "prediction committed" state

  hhUseEffect(() => {
    document.documentElement.lang = t.locale;
    document.documentElement.dir  = t.locale === 'en' ? 'ltr' : 'rtl';
  }, [t.locale]);

  // Featured card tap → open the unified MyCardsDetailModal. In production
  // this would navigate to /my-cards?focus=ID instead.
  const onCardPick = (featuredItem) => {
    if (featuredItem._inventoryItem) {
      setModalItem(featuredItem._inventoryItem);
      return;
    }
    if (typeof window.toInventoryItem === 'function' &&
        typeof window.playerCardPropsToCard === 'function') {
      const _r = (v) => v == null ? ''
                     : typeof v === 'string' ? v
                     : (v[t.locale] || v.fa || v.en || '');
      const card = window.playerCardPropsToCard({
        tier: featuredItem.tier,
        position: featuredItem.position,
        overall: featuredItem.overall,
        statKey: featuredItem.statKey,
        statValue: featuredItem.statValue,
        playerName: _r(featuredItem.playerName),
        teamName:   _r(featuredItem.teamName),
        playerImage: featuredItem.image,
      });
      const item = window.toInventoryItem({
        type: 'player', card,
        acquiredAt: new Date().toISOString(),
        status: 'available', isPinned: false,
      });
      setModalItem(item);
    }
  };

  // Prediction CTA — in production this would post to /predictions and
  // navigate to a confirmation sheet. Here we just remember it for the demo.
  const onPredict = ({ matchId, outcome }) => {
    setPredicted({ matchId, outcome });
  };
  const onAllMatches = () => { /* would route to Prediction tab */ };
  const onSubmit     = () => { /* would route to Lineup builder */ };
  const onShop       = () => { /* would route to Shop */ };

  return (
    <React.Fragment>
      <DesignCanvas>
        {/* ── Mobile Bento — the only mobile direction (Classic dropped) ── */}
        <DCSection id="mobile-bento"
                   title="Mobile · Home Hub (Bento)"
                   subtitle="چینش بر اساس Loop واقعی محصول: Prediction (ورودی اقتصاد) → سکه/پک → کارت → ترکیب/Submit → XP. Hero بازی قابل پیش‌بینی است (دکمه‌های ۱/X/۲) — ساخت ترکیب در کاشی جدا قرار گرفته.">
          <DCArtboard id="mb-default" label="A · Default (Active player)" width={420} height={2020}>
            <HHPhone w={420} h={2020}>
              <MobileBento locale={t.locale}
                           avatarSide={t.avatarSide}
                           fiveTabs={t.fiveTabs}
                           scrollAware={t.scrollAware}
                           dateMode={t.dateMode}
                           notifSimulate={t.notifSimulate}
                           showEmpty={t.showEmpty}
                           onCardPick={onCardPick}
                           onPredict={onPredict}
                           onAllMatches={onAllMatches}
                           onSubmit={onSubmit}
                           onShop={onShop}/>
            </HHPhone>
          </DCArtboard>
          <DCArtboard id="mb-shrunk" label="B · Scrolled (BottomNav shrunk)" width={420} height={920}>
            <HHPhone w={420} h={920}>
              <MobileBentoForceShrunk locale={t.locale}
                                      avatarSide={t.avatarSide}
                                      fiveTabs={t.fiveTabs}
                                      dateMode={t.dateMode}
                                      notifSimulate={t.notifSimulate}
                                      onCardPick={onCardPick}
                                      onPredict={onPredict}
                                      onAllMatches={onAllMatches}
                                      onSubmit={onSubmit}/>
            </HHPhone>
          </DCArtboard>
          <DCArtboard id="mb-empty" label="C · Empty state (تازه‌وارد)" width={420} height={920}>
            <HHPhone w={420} h={920}>
              <MobileBento locale={t.locale}
                           avatarSide={t.avatarSide}
                           fiveTabs={t.fiveTabs}
                           scrollAware={t.scrollAware}
                           dateMode={t.dateMode}
                           notifSimulate={false}
                           showEmpty={true}/>
            </HHPhone>
          </DCArtboard>
        </DCSection>

        {/* ── Desktop Bento ── */}
        <DCSection id="desktop"
                   title="Desktop · Bento Dashboard (۱۴۰۰)"
                   subtitle="چینش ۱۲ ستونه. ردیف ۱: Hero پیش‌بینی (۷) + استک Coin/Submit (۵). ردیف ۲: استتس‌ها (۱۲). ردیف ۳: کارت‌های ویژه (۱۲). ردیف ۴: Mission (۷) + QA (۵). ردیف ۵: Dailies (۷) + Pack (۵). ردیف ۶: Sponsor (۱۲).">
          <DCArtboard id="d-default" label="A · Default" width={1400} height={1500}>
            <div className="hh-desktop-frame">
              <DesktopBento locale={t.locale}
                            fiveTabs={t.fiveTabs}
                            dateMode={t.dateMode}
                            showEmpty={t.showEmpty}
                            onCardPick={onCardPick}
                            onPredict={onPredict}
                            onAllMatches={onAllMatches}
                            onSubmit={onSubmit}
                            onShop={onShop}/>
            </div>
          </DCArtboard>
          <DCArtboard id="d-empty" label="B · Empty state (تازه‌وارد)" width={1400} height={900}>
            <div className="hh-desktop-frame">
              <DesktopBento locale={t.locale}
                            fiveTabs={t.fiveTabs}
                            dateMode={t.dateMode}
                            showEmpty={true}/>
            </div>
          </DCArtboard>
        </DCSection>

        {/* ── Primitives reference for the next sprints ── */}
        <DCSection id="primitives"
                   title="Primitives · مرجع برای صفحات بعدی"
                   subtitle="AppBar / BottomNav / PredictionSlider / SubmitStatusTile / CoinPackTile / GoldenMission / DailyMission — جدا برای reuse در Prediction, Shop, Lineup, ...">
          <DCArtboard id="p-appbar" label="AppBar Variants" width={420} height={300}>
            <PrimitiveStack>
              <PrimitiveLabel text="AppBar · comfortable"/>
              <AppBar locale={t.locale} user={HH_USER} density="comfortable"
                      avatarSide={t.avatarSide}
                      notifications={t.notifSimulate ? 3 : 0}/>
              <div style={{ height: 12 }}></div>
              <PrimitiveLabel text="AppBar · compact (default for Bento — سطح + سکه)"/>
              <AppBar locale={t.locale} user={HH_USER} density="compact"
                      avatarSide={t.avatarSide}
                      showStreak={false} showXP={true}
                      notifications={t.notifSimulate ? 3 : 0}/>
              <div style={{ height: 12 }}></div>
              <PrimitiveLabel text="AppBar · avatar at end"/>
              <AppBar locale={t.locale} user={HH_USER} density="comfortable"
                      avatarSide="end"
                      notifications={t.notifSimulate ? 3 : 0}/>
            </PrimitiveStack>
          </DCArtboard>
          <DCArtboard id="p-bottomnav" label="BottomNav · Floating Pill" width={420} height={560}>
            <PrimitiveStack>
              <PrimitiveLabel text="۶ تب · expanded (حالت پیش‌فرض)"/>
              <BottomNav locale={t.locale} activeTab="home" fiveTabs={false}/>
              <div style={{ height: 18 }}></div>

              <PrimitiveLabel text="۶ تب · shrunk (با اسکرول)"/>
              <BottomNav locale={t.locale} activeTab="home" fiveTabs={false} shrunk={true}/>
              <div style={{ height: 18 }}></div>

              <PrimitiveLabel text="۵ تب · expanded (My Cards از AppBar)"/>
              <BottomNav locale={t.locale} activeTab="home" fiveTabs={true}/>
              <div style={{ height: 18 }}></div>

              <PrimitiveLabel text="۵ تب · shrunk"/>
              <BottomNav locale={t.locale} activeTab="home" fiveTabs={true} shrunk={true}/>
            </PrimitiveStack>
          </DCArtboard>
          <DCArtboard id="p-hero" label="PredictionSlider" width={420} height={460}>
            <PrimitiveStack>
              <PredictionSlider locale={t.locale}
                                matches={HH_PREDICTIONS.matches}
                                sponsorId="mci"
                                dateMode={t.dateMode}
                                nextLock={HH_PREDICTIONS.nextLock}
                                rewardTotal={HH_PREDICTIONS.rewardTotal}
                                dense={true}
                                onPredict={onPredict}
                                onAllMatches={onAllMatches}/>
            </PrimitiveStack>
          </DCArtboard>
          <DCArtboard id="p-loop-tiles" label="Loop tiles · Coin/Pack + Submit" width={420} height={380}>
            <PrimitiveStack>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <CoinPackTile locale={t.locale}
                              coinBalance={HH_USER.coinBalance}
                              freePacks={1} onCta={onShop}/>
                <SubmitStatusTile locale={t.locale} deck={HH_DECK} onCta={onSubmit}/>
              </div>
            </PrimitiveStack>
          </DCArtboard>
          <DCArtboard id="p-mission" label="Missions" width={420} height={520}>
            <PrimitiveStack>
              <GoldenMissionCard locale={t.locale}/>
              <div style={{ height: 8 }}></div>
              <DailyMissionRow locale={t.locale} mission={HH_MISSIONS.daily[0]}/>
              <DailyMissionRow locale={t.locale} mission={HH_MISSIONS.daily[1]}/>
            </PrimitiveStack>
          </DCArtboard>
        </DCSection>
      </DesignCanvas>

      {/* Live modal — opens when a featured card is tapped */}
      {window.MyCardsDetailModal && (
        <window.MyCardsDetailModal
          open={!!modalItem}
          item={modalItem}
          locale={t.locale}
          layout="sheet"
          containerWidth={window.innerWidth || 420}
          onClose={() => setModalItem(null)}
          onAddToLineup={() => setModalItem(null)}
          onViewHistory={() => {}}
          onShare={() => {}}
        />
      )}

      <TweaksPanel title="Tweaks · Home Hub">
        <TweakSection label="نمایش">
          <TweakRadio label="زبان" value={t.locale}
            options={[
              { value: 'fa', label: 'فا' },
              { value: 'en', label: 'EN' },
              { value: 'ar', label: 'ع' },
            ]}
            onChange={(v) => setTweak('locale', v)}/>
          <TweakToggle label="حالت Empty (تازه‌وارد)"
                       value={t.showEmpty}
                       onChange={(v) => setTweak('showEmpty', v)}/>
          <TweakToggle label="شبیه‌سازی اعلان جدید (dot)"
                       value={t.notifSimulate}
                       onChange={(v) => setTweak('notifSimulate', v)}/>
        </TweakSection>

        <TweakSection label="AppBar">
          <TweakRadio label="سمت آواتار" value={t.avatarSide}
            options={[
              { value: 'start', label: 'راست (RTL)' },
              { value: 'end',   label: 'چپ' },
            ]}
            onChange={(v) => setTweak('avatarSide', v)}/>
        </TweakSection>

        <TweakSection label="BottomNav">
          <TweakRadio label="تعداد تب" value={t.fiveTabs ? '5' : '6'}
            options={[
              { value: '6', label: '۶ تب' },
              { value: '5', label: '۵ تب' },
            ]}
            onChange={(v) => setTweak('fiveTabs', v === '5')}/>
          <TweakToggle label="Scroll-aware (shrink با اسکرول)"
                       value={t.scrollAware}
                       onChange={(v) => setTweak('scrollAware', v)}/>
        </TweakSection>

        <TweakSection label="تاریخ">
          <TweakRadio label="فرمت تاریخ" value={t.dateMode}
            options={[
              { value: 'jalali',    label: 'شمسی' },
              { value: 'gregorian', label: 'میلادی' },
              { value: 'hybrid',    label: 'ترکیبی' },
            ]}
            onChange={(v) => setTweak('dateMode', v)}/>
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

// Force-shrunk Bento variant — scrolled+shrunk preview
function MobileBentoForceShrunk(props) {
  const { locale, avatarSide, fiveTabs, dateMode, notifSimulate, onCardPick,
          onPredict, onAllMatches, onSubmit, notifications = 3 } = props;
  const ll = HH_I18N[locale];
  const featured = hhUseMemo(() => hhFeatured(locale), [locale]);
  return (
    <div className="hh-screen">
      <div className="hh-screen-scroll hh-screen-scroll--bento">
        <AppBar locale={locale} user={HH_USER} density="compact"
                avatarSide={avatarSide}
                showStreak={false} showXP={true}
                notifications={notifSimulate ? notifications : 0}/>
        <div className="hh-bento-body">
          <div className="hh-bento-grid">
            <div className="hh-bento-tile hh-bento-tile--hero">
              <PredictionSlider locale={locale}
                                matches={HH_PREDICTIONS.matches}
                                sponsorId="mci"
                                dateMode={dateMode}
                                nextLock={HH_PREDICTIONS.nextLock}
                                rewardTotal={HH_PREDICTIONS.rewardTotal}
                                dense={true}
                                onPredict={onPredict}
                                onAllMatches={onAllMatches}/>
            </div>
            <div className="hh-bento-tile hh-bento-tile--coin">
              <CoinPackTile locale={locale} coinBalance={HH_USER.coinBalance} freePacks={1}/>
            </div>
            <div className="hh-bento-tile hh-bento-tile--submit">
              <SubmitStatusTile locale={locale} deck={HH_DECK} onCta={onSubmit}/>
            </div>
          </div>
        </div>
      </div>
      <BottomNav locale={locale} activeTab="home" shrunk={true} fiveTabs={fiveTabs}/>
    </div>
  );
}

// ─── Primitive helper components ─────────────────────────────────────────
function PrimitiveStack({ children }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      padding: 14,
      overflow: 'auto',
      background: 'var(--bg-deep)',
      display: 'flex', flexDirection: 'column',
    }}>{children}</div>
  );
}
function PrimitiveLabel({ text }) {
  return (
    <div style={{
      fontSize: 10, color: 'var(--text-tertiary)',
      marginBottom: 6,
      fontFamily: 'JetBrains Mono, ui-monospace, monospace',
      letterSpacing: '0.04em',
    }}>{text}</div>
  );
}

// ─── Exports for unified app shell (Phase 1) ─────────────────────────────────
// MobileBento / DesktopBento are already exported from homehub-layouts.jsx.
// We export HHPhone here so the shell can wrap mobile screens in the phone frame.
Object.assign(window, { HHPhone, MobileBentoForceShrunk });

const __hhRoot = document.getElementById('root');
if (__hhRoot && !window.__APP_SHELL_MODE) {
  ReactDOM.createRoot(__hhRoot).render(<HHApp />);
}

const HH_APP_CSS = `
  .hh-phone {
    position: relative;
    background: var(--bg-deep);
    overflow: hidden;
    border-radius: 0;
  }
  .hh-phone-inner {
    position: absolute;
    inset: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  .hh-phone-inner > * { flex: 1 1 auto; min-height: 0; }
  .hh-desktop-frame {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: var(--bg-deep);
    color: var(--text-primary);
    display: flex;
    flex-direction: column;
  }
`;
const __hhAppStyle = document.createElement('style');
__hhAppStyle.textContent = HH_APP_CSS;
document.head.appendChild(__hhAppStyle);
