/* products.jsx — the Products page (§5.2): catalog home, empty + populated,
   export menu, notices band, import history. Exported to window as ProductsPage. */

var { Button, Eyebrow, Notice } = window.WiggleverseDesignSystem_94cd80 || {};

const { useState: _pUseState, useRef: _pUseRef, useEffect: _pUseEffect } = React;

/* ---- real file download helpers (makes PUC-11 / PUC-9 tangible) ---- */
function downloadText(filename, text) {
  const blob = new Blob([text], { type: 'text/csv;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = filename; document.body.appendChild(a); a.click();
  document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 1000);
}

const SAMPLE_CSV = [
  'Handle,Title,Description,Vendor,Type,Tags,Status,Published,Option1 Name,Option1 Value,Option2 Name,Option2 Value,Variant SKU,Variant Price,Variant Cost,Variant Inventory Qty,Image Src,Image Position,Image Alt Text',
  'alpine-fleece-pullover,Alpine Fleece Pullover,"<p>Brushed recycled fleece, cut for layering.</p>",Wander & Wool,standalone,"outerwear, fleece",active,TRUE,Size,S,Color,Heather Grey,AFP-S-HG,88.00,34.00,12,https://cdn.example.com/alpine-front.jpg,1,Alpine fleece — front',
  'alpine-fleece-pullover,,,,,,,,Size,M,Color,Heather Grey,AFP-M-HG,88.00,34.00,9,,,',
  'alpine-fleece-pullover,,,,,,,,Size,L,Color,Forest,AFP-L-FO,88.00,34.00,7,https://cdn.example.com/alpine-forest.jpg,2,Alpine fleece — forest',
  'harbor-tote,Harbor Canvas Tote,"<p>Heavyweight organic-canvas tote.</p>",Wander & Wool,standalone,"bags, accessories",active,TRUE,,,,,HCT-01,48.00,18.00,40,https://cdn.example.com/harbor-tote.jpg,1,Harbor tote',
].join('\n');

function StatusFilterMenu({ onExport, onClose }) {
  const [status, setStatus] = _pUseState('all');
  const opts = [['all', 'All products'], ['active', 'Active'], ['draft', 'Draft'], ['archived', 'Archived']];
  const ref = _pUseRef(null);
  _pUseEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  return (
    <div ref={ref} style={{
      position: 'absolute', top: 'calc(100% + .5rem)', right: 0, zIndex: 40, width: 246,
      background: 'var(--surface-card-light)', border: '1px solid var(--paper-line-strong)',
      borderRadius: '12px', boxShadow: '0 12px 32px rgba(14,18,48,.16)', padding: '.7rem',
    }}>
      <div style={{ fontSize: '.72rem', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--text-on-light-soft)', padding: '.3rem .4rem .5rem' }}>Export — filter by status</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '.1rem' }}>
        {opts.map(([v, label]) => (
          <button key={v} onClick={() => setStatus(v)} style={{
            display: 'flex', alignItems: 'center', gap: '.6rem', padding: '.5rem .5rem', borderRadius: 8,
            border: 'none', background: status === v ? 'var(--violet-tint)' : 'transparent', cursor: 'pointer',
            font: 'inherit', fontSize: '.92rem', color: 'var(--text-on-light)', textAlign: 'left',
          }}>
            <span style={{
              width: 16, height: 16, borderRadius: 999, flexShrink: 0,
              border: `1.5px solid ${status === v ? 'var(--wv-violet)' : 'var(--paper-line-strong)'}`,
              display: 'grid', placeItems: 'center',
            }}>
              {status === v && <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--wv-violet)' }} />}
            </span>
            {label}
          </button>
        ))}
      </div>
      <div style={{ borderTop: '1px solid var(--paper-line)', marginTop: '.5rem', paddingTop: '.6rem' }}>
        <button onClick={() => onExport(status)} style={{
          width: '100%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: '.45em',
          fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: '.92rem', color: 'var(--cta-text)',
          background: 'var(--cta)', border: 'none', borderRadius: 999, padding: '.55rem 1rem', cursor: 'pointer', whiteSpace: 'nowrap',
        }}>
          <Icon name="download" size={15} /> Download CSV
        </button>
      </div>
    </div>
  );
}

function HistoryStatus({ status }) {
  const map = {
    applying: ['Importing…', 'var(--wv-violet)', true],
    fetching_images: ['Fetching images…', 'var(--wv-violet)', true],
    complete: ['Complete', 'var(--st-add)', false],
    complete_with_problems: ['Complete · problems', 'var(--st-update)', false],
  };
  const [label, color, spin] = map[status] || map.complete;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: '.4em', fontSize: '.84rem', fontWeight: 600, color }}>
      {spin ? <Spinner size={13} /> : <span style={{ width: 7, height: 7, borderRadius: 999, background: color }} />}
      {label}
    </span>
  );
}

function ImportHistory({ runs, onOpenRun }) {
  return (
    <section style={{ marginTop: '2.4rem' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: '.7rem', marginBottom: '.9rem' }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: '1.25rem', color: 'var(--text-on-light)', margin: 0 }}>Import history</h2>
        <span style={{ fontSize: '.88rem', color: 'var(--text-on-light-soft)' }}>{runs.length} runs · newest first</span>
      </div>
      <Card pad="0" style={{ overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '.9rem' }}>
          <thead>
            <tr style={{ textAlign: 'left', color: 'var(--text-on-light-soft)', fontSize: '.74rem', textTransform: 'uppercase', letterSpacing: '.06em' }}>
              <th style={{ padding: '.85rem 1.2rem', fontWeight: 600 }}>When</th>
              <th style={{ padding: '.85rem 1.2rem', fontWeight: 600 }}>File</th>
              <th style={{ padding: '.85rem 1.2rem', fontWeight: 600 }}>Dialect</th>
              <th style={{ padding: '.85rem 1.2rem', fontWeight: 600, textAlign: 'right' }}>Added / Updated / Errors</th>
              <th style={{ padding: '.85rem 1.2rem', fontWeight: 600 }}>Images</th>
              <th style={{ padding: '.85rem 1.2rem', fontWeight: 600 }}>Status</th>
            </tr>
          </thead>
          <tbody>
            {runs.map((r, i) => (
              <tr key={r.id} onClick={() => onOpenRun(r.id)} className="ie-hrow" style={{
                borderTop: '1px solid var(--paper-line)', cursor: 'pointer',
              }}>
                <td style={{ padding: '.95rem 1.2rem', color: 'var(--text-on-light-soft)', whiteSpace: 'nowrap' }}>{r.rel}</td>
                <td style={{ padding: '.95rem 1.2rem' }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: '.45em', color: 'var(--text-on-light)', fontWeight: 500 }}>
                    <Icon name="file" size={15} style={{ color: 'var(--wv-violet)' }} /> {r.file}
                  </span>
                </td>
                <td style={{ padding: '.95rem 1.2rem', color: 'var(--text-on-light-soft)' }}>{r.dialect}</td>
                <td style={{ padding: '.95rem 1.2rem', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                  <span style={{ color: 'var(--st-add)', fontWeight: 600 }}>+{r.added}</span>
                  <span style={{ color: 'var(--text-on-light-soft)', margin: '0 .35em' }}>·</span>
                  <span style={{ color: 'var(--st-update)', fontWeight: 600 }}>±{r.updated}</span>
                  <span style={{ color: 'var(--text-on-light-soft)', margin: '0 .35em' }}>·</span>
                  <span style={{ color: r.errors ? 'var(--st-error)' : 'var(--text-on-light-soft)', fontWeight: 600 }}>!{r.errors}</span>
                </td>
                <td style={{ padding: '.95rem 1.2rem', color: 'var(--text-on-light-soft)', whiteSpace: 'nowrap' }}>
                  {(r.images.fetched + r.images.rejected + r.images.failed) > 0
                    ? <span><span style={{ color: 'var(--st-add)' }}>{r.images.fetched} ✓</span> · <span style={{ color: 'var(--st-error)' }}>{r.images.rejected + r.images.failed} ✗</span></span>
                    : <span style={{ opacity: .6 }}>—</span>}
                </td>
                <td style={{ padding: '.95rem 1.2rem' }}><HistoryStatus status={r.status} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </section>
  );
}

function ProductsPage({ data, catalogEmpty, onImport, onOpenRun, toast }) {
  const { STOREFRONT, HISTORY } = data;
  const [menuOpen, setMenuOpen] = _pUseState(false);
  const count = catalogEmpty ? 0 : STOREFRONT.productCount;
  const runs = catalogEmpty ? [] : HISTORY;

  const doExport = (status) => {
    setMenuOpen(false);
    toast(`Exporting ${status === 'all' ? 'all' : status} products…`);
    setTimeout(() => {
      const header = SAMPLE_CSV.split('\n')[0];
      downloadText(`wander-wool-catalog-${status}.csv`, header + '\n' + SAMPLE_CSV.split('\n').slice(1).join('\n'));
      toast(`Exported ${count.toLocaleString()} products → wander-wool-catalog-${status}.csv`, 'success');
    }, 900);
  };

  return (
    <div>
      {/* header row */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: '1rem', flexWrap: 'wrap' }}>
        <div>
          <Eyebrow onLight>Catalog</Eyebrow>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: '2.1rem', letterSpacing: '-0.015em', color: 'var(--text-on-light)', margin: '.35rem 0 0' }}>
            Products <span style={{ color: 'var(--text-on-light-soft)', fontWeight: 500 }}>· {count.toLocaleString()}</span>
          </h1>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '.7rem', position: 'relative' }}>
          <div style={{ position: 'relative' }}>
            <button onClick={() => !catalogEmpty && setMenuOpen((o) => !o)} disabled={catalogEmpty} title={catalogEmpty ? 'Nothing to export yet' : ''} style={{
              display: 'inline-flex', alignItems: 'center', gap: '.45em', fontFamily: 'var(--font-display)',
              fontWeight: 500, fontSize: '.92rem', color: 'var(--text-on-light)', background: 'var(--surface-card-light)',
              border: '1.5px solid var(--paper-line-strong)', borderRadius: 999, padding: '.55rem 1.1rem',
              cursor: catalogEmpty ? 'not-allowed' : 'pointer', opacity: catalogEmpty ? .5 : 1,
            }}>
              <Icon name="download" size={16} /> Export <Icon name="chevronDown" size={14} />
            </button>
            {menuOpen && <StatusFilterMenu onExport={doExport} onClose={() => setMenuOpen(false)} />}
          </div>
          <Button variant="primary" onClick={onImport}>
            <Icon name="upload" size={16} /> Import products
          </Button>
        </div>
      </div>

      {catalogEmpty
        ? <span style={{ display: 'block', fontSize: '.9rem', color: 'var(--text-on-light-soft)', marginTop: '.5rem' }}>An honest empty shell — nothing to manage yet.</span>
        : <span style={{ display: 'block', fontSize: '.9rem', color: 'var(--text-on-light-soft)', marginTop: '.5rem' }}>One canonical CSV in, your whole catalog out — any time.</span>}

      {/* notices band */}
      {!catalogEmpty && STOREFRONT.imageProblemCount > 0 && (
        <button onClick={() => onOpenRun(STOREFRONT.latestRunId)} style={{
          display: 'flex', alignItems: 'center', gap: '.7rem', width: '100%', textAlign: 'left',
          marginTop: '1.5rem', padding: '.85rem 1.1rem', borderRadius: '12px', cursor: 'pointer',
          background: 'var(--st-update-tint)', border: '1px solid var(--st-update-line)', font: 'inherit',
        }}>
          <Icon name="image" size={18} style={{ color: 'var(--st-update)' }} />
          <span style={{ flex: 1, color: 'var(--text-on-light)', fontSize: '.92rem' }}>
            <strong style={{ fontWeight: 600 }}>{STOREFRONT.imageProblemCount} products have image problems.</strong>
            <span style={{ color: 'var(--text-on-light-soft)' }}> Some images were rejected or unreachable in your latest import.</span>
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: '.3em', color: 'var(--st-update)', fontWeight: 600, fontSize: '.88rem' }}>
            View run <Icon name="arrowRight" size={14} />
          </span>
        </button>
      )}

      {/* primary content */}
      {catalogEmpty ? (
        <Card style={{ marginTop: '1.8rem', padding: '3rem 2rem', textAlign: 'center' }}>
          <div style={{ width: 56, height: 56, margin: '0 auto 1.1rem', borderRadius: 16, background: 'var(--violet-tint)', display: 'grid', placeItems: 'center' }}>
            <Icon name="products" size={26} style={{ color: 'var(--wv-violet)' }} />
          </div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: '1.4rem', color: 'var(--text-on-light)', margin: '0 0 .4rem' }}>No products yet</h2>
          <p style={{ fontSize: '1rem', color: 'var(--text-on-light-soft)', maxWidth: '40ch', margin: '0 auto 1.5rem', lineHeight: 1.55 }}>
            Bulk import is how product data gets in. Bring a CSV — yours, or an export from your old platform — and your catalog becomes your storefront.
          </p>
          <Button variant="primary" onClick={onImport}>
            <Icon name="upload" size={16} /> Import products
          </Button>
          <div style={{ display: 'flex', gap: '1.6rem', justifyContent: 'center', marginTop: '1.5rem' }}>
            <a onClick={(e) => { e.preventDefault(); downloadText('wander-wool-sample.csv', SAMPLE_CSV); toast('Sample CSV downloaded', 'success'); }} href="#" style={{ display: 'inline-flex', alignItems: 'center', gap: '.35em', color: 'var(--wv-violet)', fontWeight: 500, fontSize: '.9rem', textDecoration: 'none' }}>
              <Icon name="download" size={14} /> Download sample CSV
            </a>
            <a onClick={(e) => e.preventDefault()} href="#" style={{ display: 'inline-flex', alignItems: 'center', gap: '.35em', color: 'var(--wv-violet)', fontWeight: 500, fontSize: '.9rem', textDecoration: 'none' }}>
              <Icon name="link" size={14} /> Column reference
            </a>
          </div>
        </Card>
      ) : (
        <Card style={{ marginTop: '1.8rem', display: 'flex', alignItems: 'center', gap: '1.2rem', padding: '1.4rem 1.6rem' }}>
          <div style={{ width: 46, height: 46, flexShrink: 0, borderRadius: 12, background: 'var(--add-tint)', display: 'grid', placeItems: 'center' }}>
            <Icon name="check" size={22} style={{ color: 'var(--st-add)' }} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: '1.05rem', color: 'var(--text-on-light)' }}>Your catalog is loaded — {count.toLocaleString()} products.</div>
            <div style={{ fontSize: '.92rem', color: 'var(--text-on-light-soft)', marginTop: '.15rem' }}>The browsable product list arrives with an upcoming release. For now, manage it in bulk: import to change it, export to take it.</div>
          </div>
          <span style={{ whiteSpace: 'nowrap' }}><Notice>List · soon</Notice></span>
        </Card>
      )}

      {/* history */}
      {runs.length > 0
        ? <ImportHistory runs={runs} onOpenRun={onOpenRun} />
        : !catalogEmpty ? null : (
          <section style={{ marginTop: '2.4rem' }}>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: '1.25rem', color: 'var(--text-on-light)', margin: '0 0 .9rem' }}>Import history</h2>
            <Card style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-on-light-soft)' }}>No imports yet.</Card>
          </section>
        )}
    </div>
  );
}

window.ProductsPage = ProductsPage;
window.IE_downloadText = downloadText;
window.IE_SAMPLE_CSV = SAMPLE_CSV;
