// mycards-app.jsx — Wires My Cards screens into the design canvas and Tweaks panel.

const { useState, useMemo, useEffect, useRef } = React;

// ─── Single inventory screen (mobile + desktop share most of it) ───────────
// Variants are now fixed per viewport (decided in the design log):
//   • Mobile  → summary='chips', type tabs='underline', filters='dropdown'
//   • Desktop → summary='tiles', type tabs='pill',      filters='chip rows'
// Props left:
//   density (2|3|4)  — grid columns
//   showEmpty        — force empty state
//   locale           — 'fa' | 'en' | 'ar'
//   view             — 'grid' | 'list'
//   onPick(item)     — opens detail modal
function InventoryScreen({
  locale = 'fa',
  density = 2,
  showEmpty = false,
  view = 'grid',
  onPick,
  desktop = false,
}) {
  const ll = MC_I18N[locale];
  const [type, setType]       = useState('all');
  const [tier, setTier]       = useState('all');
  const [position, setPos]    = useState('all');
  const [status, setStatus]   = useState('all');
  const [search, setSearch]   = useState('');
  const [sort, setSort]       = useState('overall');
  const [viewMode, setView]   = useState(view);
  useEffect(() => setView(view), [view]);

  // Per-viewport fixed variants
  const summaryVariant  = desktop ? 'tiles'     : 'chips';
  const typeTabVariant  = desktop ? 'pill'      : 'underline';
  const chipVariant     = 'pill';     // desktop filter chips style

  // Recompute filtered set
  const counts = useMemo(() => inventoryCounts(INVENTORY), []);
  const filtered = useMemo(
    () => applyFilters(INVENTORY, { type, tier, position, status, search, locale }),
    [type, tier, position, status, search, locale]
  );
  const sorted = useMemo(() => applySort(filtered, sort, locale), [filtered, sort, locale]);

  const tierChips = [
    { key: 'all',      label: ll.tabAll, short: ll.tabAll },
    { key: 'platinum', label: TIER.platinum.name[locale], short: TIER.platinum.name[locale],
      color: TIER.platinum.base, dot: true, count: counts.platinum },
    { key: 'gold',     label: TIER.gold.name[locale], short: TIER.gold.name[locale],
      color: TIER.gold.base,     dot: true, count: counts.gold },
    { key: 'silver',   label: TIER.silver.name[locale], short: TIER.silver.name[locale],
      color: TIER.silver.base,   dot: true, count: counts.silver },
    { key: 'bronze',   label: TIER.bronze.name[locale], short: TIER.bronze.name[locale],
      color: TIER.bronze.base,   dot: true, count: counts.bronze },
  ];
  const posChips = [
    { key: 'all', label: ll.tabAll, short: ll.tabAll },
    { key: 'GK',  label: I18N[locale].pos.GK,  short: I18N[locale].posShort.GK },
    { key: 'DEF', label: I18N[locale].pos.DEF, short: I18N[locale].posShort.DEF },
    { key: 'MID', label: I18N[locale].pos.MID, short: I18N[locale].posShort.MID },
    { key: 'FWD', label: I18N[locale].pos.FWD, short: I18N[locale].posShort.FWD },
  ];
  const statusChips = [
    { key: 'all',       label: ll.tabAll, short: ll.tabAll },
    { key: 'available', label: ll.statusAvailable, short: ll.statusAvailable,
      color: '#34D399', dot: true, count: counts.available },
    { key: 'reserved',  label: ll.statusReserved, short: ll.statusReserved,
      color: '#7163D9', dot: true, count: counts.reserved },
    { key: 'expired',   label: ll.statusExpired, short: ll.statusExpired,
      color: '#6B6960', dot: true, count: counts.expired },
  ];

  // Build grid items with sponsor insertion every 8 cards.
  // Desktop hides inline sponsors (the sidebar already runs the sponsor rail);
  // mobile keeps them so the in-grid placement still surfaces brands.
  const desktopCols = 4;                                            // fixed
  const gridDensity = desktop ? desktopCols : density;
  const showInlineSponsors = !desktop;
  const renderItems = (items) => {
    if (showEmpty || items.length === 0) {
      if (showEmpty) return <EmptyState locale={locale} onCta={() => {}} />;
      return (
        <div className="mc-noresult">
          <div className="mc-noresult-text">
            {locale === 'fa' ? 'هیچ کارتی با این فیلتر پیدا نشد' :
             locale === 'ar' ? 'لا توجد بطاقات بهذا الفلتر' :
             'No cards match this filter'}
          </div>
        </div>
      );
    }
    if (viewMode === 'list') {
      const rows = [];
      items.forEach((it, i) => {
        rows.push(<ListRow key={it.instance_id} item={it} locale={locale} onClick={onPick} />);
        if (showInlineSponsors && (i + 1) % 8 === 0 && i !== items.length - 1) {
          rows.push(
            <InlineSponsor key={`sp-${i}`} locale={locale}
              sponsorId={['mci','blu','mili'][Math.floor(i / 8) % 3]} spans={1}/>
          );
        }
      });
      return <div className="mc-list">{rows}</div>;
    }
    // grid
    const cells = [];
    items.forEach((it, i) => {
      cells.push(
        <GridCard key={it.instance_id} item={it} locale={locale}
                  onClick={onPick} isPinned={it.isPinned} density={gridDensity}/>
      );
      if (showInlineSponsors && (i + 1) % 8 === 0 && i !== items.length - 1) {
        cells.push(
          <InlineSponsor key={`sp-${i}`} locale={locale}
            sponsorId={['mci','blu','mili'][Math.floor(i / 8) % 3]} spans={gridDensity}/>
        );
      }
    });
    return (
      <div className={`mc-grid mc-grid--d${gridDensity}`}>{cells}</div>
    );
  };

  return (
    <div className={`mc-screen ${desktop ? 'mc-screen--desktop' : ''}`}>
      <MCHeader locale={locale} count={counts.all} onBack={() => {}} dense={desktop}/>

      {desktop ? (
        // Desktop: 2-column — left sidebar (summary + sponsor blocks),
        // right main column (tabs + dropdown filters + search/sort + 3-col grid).
        <div className="mc-desktop-grid">
          <aside className="mc-desktop-sidebar">
            <div className="mc-side-block">
              <div className="mc-side-block-label">{ll.countTotal}</div>
              <SummaryStrip locale={locale} counts={counts} variant={summaryVariant} />
            </div>
            <SponsorBlock locale={locale} sponsorId="mci" />
            <SponsorBlock locale={locale} sponsorId="blu" />
            <SponsorBlock locale={locale} sponsorId="mili" />
          </aside>
          <main className="mc-desktop-main">
            <TypeTabs locale={locale} value={type} onChange={setType}
                      counts={counts} variant={typeTabVariant}/>
            <div className="mc-filter-row">
              <FilterDropdown label={ll.filterStatus} value={status} options={statusChips}
                              onChange={setStatus} locale={locale}/>
              <FilterDropdown label={ll.filterTier}   value={tier}   options={tierChips}
                              onChange={setTier}   locale={locale}/>
              <FilterDropdown label={ll.filterPosition} value={position} options={posChips}
                              onChange={setPos}    locale={locale}/>
              <div className="mc-filter-row-grow"></div>
              <SearchInput locale={locale} value={search} onChange={setSearch}/>
              <SortMenu locale={locale} value={sort} onChange={setSort}
                        options={['overall','recent','tier','name','team','position']}/>
              <ViewToggle locale={locale} value={viewMode} onChange={setView}/>
            </div>
            <div className="mc-results">
              <div className="mc-results-meta">
                {ll.countCards(toLocaleDigits(sorted.length, locale))}
              </div>
              {renderItems(sorted)}
            </div>
          </main>
        </div>
      ) : (
        // Mobile: vertical stack — filters as compact dropdowns (wireframe-aligned).
        // Summary strip removed: TypeTabs counts already surface the same numbers.
        <React.Fragment>
          <TypeTabs locale={locale} value={type} onChange={setType}
                    counts={counts} variant={typeTabVariant}/>
          <SearchInput locale={locale} value={search} onChange={setSearch}/>
          <div className="mc-filter-row">
            <FilterDropdown label={ll.filterStatus} value={status} options={statusChips}
                            onChange={setStatus} locale={locale}/>
            <FilterDropdown label={ll.filterTier}   value={tier}   options={tierChips}
                            onChange={setTier}   locale={locale}/>
            <FilterDropdown label={ll.filterPosition} value={position} options={posChips}
                            onChange={setPos}    locale={locale}/>
          </div>
          <div className="mc-controls-row mc-controls-row--mobile">
            <SortMenu locale={locale} value={sort} onChange={setSort}
                      options={['overall','recent','tier','name','team','position']}/>
            <div style={{ flex: 1 }}></div>
            <ViewToggle locale={locale} value={viewMode} onChange={setView}/>
          </div>
          <div className="mc-results">
            {renderItems(sorted)}
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

// ─── A standalone "mobile frame" preview used inside artboards ────────────
function MobileFrame({ children, w = 420, h = 900, label }) {
  return (
    <div className="mc-phone" style={{ width: w, height: h }}>
      <div className="mc-phone-inner">{children}</div>
    </div>
  );
}

// ─── Modal preview helper — renders the modal *inline* over a faded screen ──
function ModalPreview({ item, locale, layout, w = 420, h = 760 }) {
  return (
    <div className="mc-phone" style={{ width: w, height: h }} data-modal-preview="true">
      <div className="mc-phone-inner mc-phone-inner--dim">
        {/* Dimmed background screen for context */}
        <div className="mc-modal-bg-faint">
          <InventoryScreenStatic locale={locale} />
        </div>
      </div>
      <MyCardsDetailModal
        open={true}
        item={item}
        locale={locale}
        layout={layout}
        containerWidth={w}
        inline={true}
        onClose={() => {}}
        onAddToLineup={() => {}}
        onViewHistory={() => {}}
        onShare={() => {}}
      />
    </div>
  );
}

// Static (non-interactive) inventory snapshot for modal-preview dim layer.
function InventoryScreenStatic({ locale }) {
  const counts = inventoryCounts(INVENTORY);
  const ll = MC_I18N[locale];
  return (
    <div className="mc-screen">
      <MCHeader locale={locale} count={counts.all} dense={false}/>
      <div className="mc-tabs mc-tabs--underline" aria-hidden="true">
        {['all','player','null','fan','coach'].map((t, i) => (
          <span key={t} className={`mc-tab ${i === 0 ? 'is-active' : ''}`}>
            <span>{ll['tab' + t[0].toUpperCase() + t.slice(1)]}</span>
            <span className="mc-tab-count">{toLocaleDigits(counts[t] ?? counts.all, locale)}</span>
          </span>
        ))}
      </div>
      <div className="mc-results">
        <div className="mc-grid mc-grid--d2">
          {INVENTORY.slice(0, 6).map((it) => (
            <GridCard key={it.instance_id} item={it} locale={locale} onClick={() => {}} density={2}/>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── App root — controls global tweaks + modal state, mounts canvas ────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "locale": "fa",
  "density": 2,
  "view": "grid",
  "modalLayout": "sheet",
  "showEmpty": false
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Lift modal so it can render in front of artboard interactions.
  const [modalItem, setModalItem] = useState(null);

  // Update <html lang/dir>
  useEffect(() => {
    document.documentElement.lang = t.locale;
    document.documentElement.dir  = t.locale === 'en' ? 'ltr' : 'rtl';
  }, [t.locale]);

  // Sample items to feature in modal previews
  const samplePlayer = INVENTORY.find((it) => it.type === 'player' && it.card.tier === 'gold' && it.card.position === 'FWD');
  const sampleCoach  = INVENTORY.find((it) => it.type === 'coach');
  const sampleFan    = INVENTORY.find((it) => it.type === 'fan');
  const sampleNull   = INVENTORY.find((it) => it.type === 'null');

  return (
    <React.Fragment>
      <DesignCanvas>
        <DCSection id="phone" title="My Cards · موبایل"
          subtitle="صفحه‌ی اصلی روی موبایل ۴۲۰ — header → summary → tabs → search → filters → grid → modal triggered by card tap">
          <DCArtboard id="m-grid" label="A · Grid (پیش‌فرض)" width={420} height={1320}>
            <MobileFrame w={420} h={1320}>
              <InventoryScreen locale={t.locale}
                density={t.density}
                showEmpty={t.showEmpty}
                view={t.view}
                onPick={(it) => setModalItem(it)}/>
            </MobileFrame>
          </DCArtboard>
          <DCArtboard id="m-list" label="B · List (لیست)" width={420} height={1320}>
            <MobileFrame w={420} h={1320}>
              <InventoryScreen locale={t.locale}
                density={t.density}
                view="list"
                onPick={(it) => setModalItem(it)}/>
            </MobileFrame>
          </DCArtboard>
          <DCArtboard id="m-empty" label="C · Empty state" width={420} height={900}>
            <MobileFrame w={420} h={900}>
              <InventoryScreen locale={t.locale}
                density={t.density}
                showEmpty={true}
                view={t.view}
                onPick={() => {}}/>
            </MobileFrame>
          </DCArtboard>
        </DCSection>

        <DCSection id="modals" title="Card Details · مودال جزئیات"
          subtitle="مودال نهایی — جایگزین نسخه‌ی provisional در Lineup picker. ۴ نوع کارت × ۳ layout (sheet / minimal / sideBySide).">
          <DCArtboard id="md-player-sheet" label="Player · Sheet (موبایل)" width={420} height={900}>
            <ModalPreview item={samplePlayer} locale={t.locale} layout="sheet" w={420} h={900}/>
          </DCArtboard>
          <DCArtboard id="md-coach-sheet" label="Coach · Sheet" width={420} height={900}>
            <ModalPreview item={sampleCoach} locale={t.locale} layout="sheet" w={420} h={900}/>
          </DCArtboard>
          <DCArtboard id="md-fan-sheet" label="Fan · Sheet" width={420} height={900}>
            <ModalPreview item={sampleFan} locale={t.locale} layout="sheet" w={420} h={900}/>
          </DCArtboard>
          <DCArtboard id="md-null-minimal" label="Null · Minimal" width={420} height={780}>
            <ModalPreview item={sampleNull} locale={t.locale} layout="minimal" w={420} h={780}/>
          </DCArtboard>
        </DCSection>

        <DCSection id="desktop" title="My Cards · دسکتاپ"
          subtitle="چینش ۲ ستونه: سایدبار (خلاصه کاشی + سه باکس اسپانسر با درخشش) + ستون اصلی (تب‌های حبه‌ای + ۳ دراپ‌داون فیلتر + جستجو + شبکه ۳ ستونه).">
          <DCArtboard id="d-grid" label="Desktop · Grid" width={1400} height={1100}>
            <div className="mc-desktop-frame">
              <InventoryScreen locale={t.locale}
                density={t.density}
                showEmpty={t.showEmpty}
                view={t.view}
                desktop={true}
                onPick={(it) => setModalItem(it)}/>
            </div>
          </DCArtboard>
          <DCArtboard id="d-modal" label="Desktop · Side-by-side modal" width={1400} height={1100}>
            <div className="mc-desktop-frame" style={{ position: 'relative' }}>
              <InventoryScreenStatic locale={t.locale}/>
              <MyCardsDetailModal
                open={true} item={samplePlayer} locale={t.locale}
                layout="sideBySide" containerWidth={1400} inline={true}
                onClose={() => {}} onAddToLineup={() => {}}
                onViewHistory={() => {}} onShare={() => {}}/>
            </div>
          </DCArtboard>
        </DCSection>
      </DesignCanvas>

      {/* Live modal (portal) — only used by interactive artboards' GridCards. */}
      <MyCardsDetailModal
        open={!!modalItem}
        item={modalItem}
        locale={t.locale}
        layout={t.modalLayout === 'auto' ? 'auto' : t.modalLayout}
        containerWidth={window.innerWidth || 420}
        onClose={() => setModalItem(null)}
        onAddToLineup={(it) => { setModalItem(null); /* would route to Lineup */ }}
        onViewHistory={(it) => { /* would open deck history sheet */ }}
        onShare={(it) => { /* would trigger screenshot share */ }}
      />

      <TweaksPanel title="Tweaks · My Cards">
        <TweakSection label="نمایش">
          <TweakRadio label="زبان" value={t.locale}
            options={[
              { value: 'fa', label: 'فا' },
              { value: 'en', label: 'EN' },
              { value: 'ar', label: 'ع' },
            ]}
            onChange={(v) => setTweak('locale', v)}/>
          <TweakRadio label="حالت نمایش" value={t.view}
            options={[
              { value: 'grid', label: 'شبکه' },
              { value: 'list', label: 'لیست' },
            ]}
            onChange={(v) => setTweak('view', v)}/>
          <TweakRadio label="ستون‌های شبکه" value={String(t.density)}
            options={[
              { value: '2', label: '۲' },
              { value: '3', label: '۳' },
              { value: '4', label: '۴' },
            ]}
            onChange={(v) => setTweak('density', parseInt(v, 10))}/>
          <TweakToggle label="حالت Empty (هیچ کارتی نداره)"
                       value={t.showEmpty}
                       onChange={(v) => setTweak('showEmpty', v)}/>
        </TweakSection>
        <TweakSection label="مودال جزئیات">
          <TweakRadio label="چینش مودال"
            value={t.modalLayout}
            options={[
              { value: 'sheet',       label: 'Sheet' },
              { value: 'minimal',     label: 'Minimal' },
              { value: 'sideBySide',  label: 'کنار هم' },
              { value: 'auto',        label: 'خودکار' },
            ]}
            onChange={(v) => setTweak('modalLayout', v)}/>
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

// ─── Exports for unified app shell (Phase 1) ─────────────────────────────────
Object.assign(window, { InventoryScreen, InventoryScreenStatic, MobileFrame });

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

// ─── styles ─────────────────────────────────────────────────────────────────
const MC_APP_CSS = `
  /* Phone frame for mobile artboard previews */
  .mc-phone {
    position: relative;
    background: var(--bg-deep);
    overflow: hidden;
    border-radius: 0;
  }
  .mc-phone-inner {
    position: absolute;
    inset: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  .mc-phone-inner--dim {
    filter: brightness(0.65) saturate(0.9);
    pointer-events: none;
  }
  .mc-modal-bg-faint {
    position: absolute;
    inset: 0;
    overflow: hidden;
  }
  .mc-modal-bg-faint > * {
    pointer-events: none;
  }

  /* Main screen scroll container */
  .mc-screen {
    width: 100%;
    height: 100%;
    overflow: auto;
    display: flex;
    flex-direction: column;
    background: var(--bg-deep);
    color: var(--text-primary);
    font-family: var(--font-current);
    scrollbar-width: thin;
  }
  .mc-screen::-webkit-scrollbar { width: 6px; }
  .mc-screen::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.08); border-radius: 3px; }

  .mc-screen--desktop {
    /* Desktop has its own grid layout */
  }

  /* Chrome elements above the results — must NOT shrink under tall children
     in the flex column. Without flex-shrink: 0, a tall .mc-results would
     compress every header/tab/search row down to its border (1px). */
  .mc-screen > .mc-header,
  .mc-screen > .mc-tabs,
  .mc-screen > .mc-search,
  .mc-screen > .mc-filter-row,
  .mc-screen > .mc-controls-row,
  .mc-screen > .mc-summary,
  .mc-screen > .mc-chips,
  .mc-desktop-main > .mc-tabs,
  .mc-desktop-main > .mc-filter-row,
  .mc-desktop-main > .mc-controls-row {
    flex-shrink: 0;
  }

  /* Mobile chip rows wrapping (so position fits below tier without horizontal scrolling) */
  .mc-row-of-rows { display: flex; }

  .mc-controls-row {
    display: flex; align-items: center; gap: 8px;
    padding: 8px 14px;
  }
  .mc-controls-row--mobile {
    padding-top: 4px;
  }

  /* Results region */
  .mc-results {
    padding: 4px 14px 24px;
    display: flex; flex-direction: column;
    gap: 10px;
  }
  .mc-results-meta {
    font-size: 11px;
    color: var(--text-tertiary);
    padding: 4px 2px 8px;
  }

  /* Grid (mobile + desktop) */
  .mc-grid {
    display: grid;
    gap: 12px;
  }
  .mc-grid--d2 { grid-template-columns: repeat(2, 1fr); }
  .mc-grid--d3 { grid-template-columns: repeat(3, 1fr); gap: 10px; }
  .mc-grid--d4 { grid-template-columns: repeat(4, 1fr); gap: 12px; }

  /* List */
  .mc-list {
    display: flex; flex-direction: column;
    gap: 8px;
  }

  /* No results filter message */
  .mc-noresult {
    padding: 48px 24px;
    text-align: center;
    color: var(--text-tertiary);
    font-size: 13px;
  }

  /* Desktop layout — 2 columns: sidebar (summary + sponsors) | main grid */
  .mc-desktop-frame {
    width: 100%; height: 100%;
    background: var(--bg-deep);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    color: var(--text-primary);
  }
  .mc-desktop-grid {
    display: grid;
    grid-template-columns: 280px 1fr;
    gap: 28px;
    padding: 24px 32px 32px;
    flex: 1 1 auto;
    min-height: 0;
    overflow: hidden;
  }
  .mc-desktop-sidebar {
    display: flex; flex-direction: column;
    gap: 18px;
    overflow-y: auto;
    padding: 4px 4px 24px;
    scrollbar-width: thin;
  }
  .mc-desktop-sidebar::-webkit-scrollbar { width: 5px; }
  .mc-desktop-sidebar::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.06); border-radius: 3px; }
  .mc-side-block {
    background: rgba(255,255,255,0.02);
    border: 1px solid rgba(255,255,255,0.05);
    border-radius: 16px;
    padding: 14px 14px 18px;
  }
  .mc-side-block-label {
    font-size: 11px;
    color: var(--text-tertiary);
    letter-spacing: 0.06em;
    text-transform: uppercase;
    font-family: 'JetBrains Mono', ui-monospace, monospace;
    margin-bottom: 10px;
  }
  html[lang="fa"] .mc-side-block-label,
  html[lang="ar"] .mc-side-block-label {
    font-family: inherit; letter-spacing: 0; text-transform: none; font-size: 12px;
  }
  /* Inside sidebar, override summary tile layout to a single column 2-up */
  .mc-desktop-sidebar .mc-summary--tiles {
    padding: 0;
    gap: 8px;
    grid-template-columns: repeat(2, 1fr);
    overflow: visible;
  }

  .mc-desktop-main {
    display: flex; flex-direction: column;
    min-width: 0;
    overflow: hidden;
  }
  .mc-desktop-main .mc-results {
    overflow-y: auto;
    flex: 1 1 auto;
    padding-right: 6px;
  }

  /* Desktop filter row — dropdowns + search + sort + view toggle on one line */
  .mc-desktop-main .mc-filter-row {
    padding: 8px 0 10px;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
  }
  .mc-filter-row-grow { flex: 1 1 auto; min-width: 0; }
  .mc-desktop-main .mc-filter-dd { flex: 0 1 180px; min-width: 140px; }
  .mc-desktop-main .mc-search { margin: 0; flex: 0 1 280px; min-width: 200px; }

  /* Override main padding for desktop */
  .mc-screen--desktop .mc-results { padding: 8px 0 24px; }
`;

const __mcAppStyle = document.createElement('style');
__mcAppStyle.textContent = MC_APP_CSS;
document.head.appendChild(__mcAppStyle);
