/* app.jsx — wires the state machine, Tweaks, and mounts. */

/* Pull every cross-file dependency off window with `var` (safe under both the
   shared-global and isolated babel-script models — no redeclaration error). */
var { AdminShell, ProductsPage, UploadScreen, PreviewScreen, RunDetailScreen } = window;
var { TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakButton, useTweaks } = window;
const { useState: _aState, useEffect: _aEffect, useRef: _aRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "catalog": "populated",
  "density": "comfortable",
  "scenario": "canonical"
}/*EDITMODE-END*/;

/* ---- synthesize image problems / errors for historical runs ---- */
function synthProblems(rejected, failed) {
  const out = [];
  const handles = ['oxford-button-down', 'weekender-duffel', 'camp-mug-enamel', 'aspen-knit-sweater', 'lantern-flannel', 'river-stone-belt', 'cedar-beanie', 'driftwood-henley'];
  for (let i = 0; i < rejected; i++) out.push({ handle: handles[i % handles.length], variant: i % 2 ? 'M / Slate' : '—', url: `https://cdn.northfield.example/${handles[i % handles.length]}-${i}.jpg`, outcome: 'rejected', reason: 'Below the resolution bar — needs at least 800 × 800.' });
  for (let i = 0; i < failed; i++) out.push({ handle: handles[(i + rejected) % handles.length], variant: '—', url: `https://oldhost.example/${handles[(i + rejected) % handles.length]}.jpg`, outcome: 'failed', reason: 'Unreachable — host timed out.' });
  return out;
}
function synthErrors(n) {
  const base = [
    { line: 88, column: 'Type', title: 'Gift Card', message: "Shopify 'Gift Card' products aren't catalog products here — skipped." },
    { line: 1042, column: 'Type', title: 'Essentials Bundle', message: 'Looks like a bundle — kits arrive in a coming release.' },
    { line: 1188, column: 'Variant Price', title: 'Trail Mug', message: "'9,00' is not a price — use a dot for decimals." },
    { line: 1455, column: 'Handle', title: '(row 1455)', message: 'Empty Handle — every row needs one.' },
  ];
  return base.slice(0, n);
}

function buildRunView(run, data) {
  if (run.id === 'run-0007') {
    return { scenario: data.SCENARIOS.canonical, images: data.IMAGE_OUTCOMES, run };
  }
  const isShopify = run.dialect.includes('Shopify');
  const scenario = {
    file: run.file,
    dialect: run.dialect + (isShopify ? ' — mapped to canonical' : ' format'),
    dialectKind: isShopify ? 'shopify' : 'canonical',
    summary: { add: run.added, update: run.updated, unchanged: 0, error: run.errors },
    records: { error: synthErrors(run.errors), add: [], update: [], unchanged: [] },
    extra: {},
    unknownColumns: [],
  };
  const total = run.images.fetched + run.images.rejected + run.images.failed;
  const images = { total, fetched: run.images.fetched, problems: synthProblems(run.images.rejected, run.images.failed) };
  return { scenario, images, run };
}

function Toast({ toast }) {
  if (!toast) return null;
  const color = toast.kind === 'success' ? 'var(--st-add)' : 'var(--wv-violet)';
  return (
    <div style={{
      position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)', zIndex: 9000,
      display: 'flex', alignItems: 'center', gap: '.55rem', padding: '.7rem 1.2rem',
      background: 'var(--wv-midnight)', color: 'var(--wv-starlight)', borderRadius: 999,
      border: '1px solid var(--wv-lilac-32)', boxShadow: '0 10px 30px rgba(9,12,34,.4)',
      fontSize: '.9rem', fontFamily: 'var(--font-body)', animation: 'ie-toast .25s ease',
    }}>
      <span style={{ width: 8, height: 8, borderRadius: 999, background: color }} />
      {toast.msg}
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [screen, setScreen] = _aState('products');
  const [view, setView] = _aState(null);
  const [toast, setToast] = _aState(null);
  const toastTimer = _aRef(null);
  const data = window.IEData;
  const catalogEmpty = t.catalog === 'empty';

  _aEffect(() => { document.documentElement.dataset.density = t.density; }, [t.density]);

  const showToast = (msg, kind) => {
    setToast({ msg, kind, id: Date.now() });
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(null), 2600);
  };

  const getImages = (scenario) => {
    const m = {
      canonical: data.IMAGE_OUTCOMES,
      shopify: { total: 519, fetched: 511, problems: synthProblems(6, 2) },
      roundtrip: { total: 0, fetched: 0, problems: [] },
    };
    return m[scenario.key] || { total: 0, fetched: 0, problems: [] };
  };

  const goProducts = () => { setScreen('products'); setView(null); };
  const goImport = () => setScreen('upload');
  const onValidated = (key) => { setView({ scenario: data.SCENARIOS[key] }); setScreen('preview'); };
  const onConfirm = (scenario) => {
    setView({ scenario, images: getImages(scenario), run: null, live: true });
    setScreen('rundetail');
    if (catalogEmpty) setTweak('catalog', 'populated');
  };
  const onOpenRun = (runId) => {
    const run = data.HISTORY.find((r) => r.id === runId);
    if (!run) return;
    setView({ ...buildRunView(run, data), live: false });
    setScreen('rundetail');
  };

  // tweak jump helpers
  const jumpPreview = () => { setView({ scenario: data.SCENARIOS[t.scenario] }); setScreen('preview'); };
  const jumpRun = () => { const sc = data.SCENARIOS[t.scenario === 'roundtrip' ? 'canonical' : t.scenario]; onConfirm(sc); };

  let body;
  if (screen === 'products') {
    body = <ProductsPage data={data} catalogEmpty={catalogEmpty} onImport={goImport} onOpenRun={onOpenRun} toast={showToast} />;
  } else if (screen === 'upload') {
    body = <UploadScreen onBack={goProducts} onValidated={onValidated} toast={showToast} />;
  } else if (screen === 'preview' && view) {
    body = <PreviewScreen scenario={view.scenario} onCancel={goProducts} onConfirm={onConfirm} />;
  } else if (screen === 'rundetail' && view) {
    body = <RunDetailScreen run={view.run} scenario={view.scenario} images={view.images} onBack={goProducts} live={view.live} />;
  } else {
    body = <ProductsPage data={data} catalogEmpty={catalogEmpty} onImport={goImport} onOpenRun={onOpenRun} toast={showToast} />;
  }

  return (
    <React.Fragment>
      <AdminShell current="products" onNav={() => goProducts()} storefront={data.STOREFRONT}>
        {body}
      </AdminShell>
      <Toast toast={toast} />

      <TweaksPanel>
        <TweakSection label="Prototype state" />
        <TweakRadio label="Catalog" value={t.catalog} options={['populated', 'empty']} onChange={(v) => { setTweak('catalog', v); setScreen('products'); setView(null); }} />
        <TweakRadio label="Density" value={t.density} options={['comfortable', 'compact']} onChange={(v) => setTweak('density', v)} />

        <TweakSection label="Jump to a step" />
        <TweakSelect label="Import file" value={t.scenario}
          options={[['canonical', 'Canonical — seasonal pricing'], ['shopify', 'Shopify export — mapped'], ['roundtrip', 'Round-trip — no-op']].map(([v, l]) => ({ value: v, label: l }))}
          onChange={(v) => setTweak('scenario', v)} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.4rem', marginTop: '.2rem' }}>
          <TweakButton label="Products" onClick={goProducts} />
          <TweakButton label="Upload" onClick={goImport} />
          <TweakButton label="Preview" onClick={jumpPreview} />
          <TweakButton label="Run detail" onClick={jumpRun} />
        </div>
      </TweaksPanel>
    </React.Fragment>
  );
}

/* Mount once everything is on window (guards against script-eval ordering). */
function ieMount() {
  const ready = window.AdminShell && window.ProductsPage && window.UploadScreen &&
    window.PreviewScreen && window.RunDetailScreen && window.TweaksPanel &&
    window.TweakSection && window.TweakRadio && window.TweakSelect && window.TweakButton &&
    window.useTweaks && window.IEData;
  if (!ready) { setTimeout(ieMount, 20); return; }
  // refresh local bindings in case they were read before the producer ran
  AdminShell = window.AdminShell; ProductsPage = window.ProductsPage;
  UploadScreen = window.UploadScreen; PreviewScreen = window.PreviewScreen;
  RunDetailScreen = window.RunDetailScreen; TweaksPanel = window.TweaksPanel;
  TweakSection = window.TweakSection; TweakRadio = window.TweakRadio;
  TweakSelect = window.TweakSelect; TweakButton = window.TweakButton; useTweaks = window.useTweaks;
  if (!window.__ieRoot) window.__ieRoot = ReactDOM.createRoot(document.getElementById('ie-root'));
  window.__ieRoot.render(<App />);
}
ieMount();
