// Catalog (department browse) + expanded Product Detail with real-image slots.
// Demonstrates: calm catalog grid, a real-image feature banner, and an
// expanded product view (hero + gallery) where Blyzr explains WHY it stocks it.

const { useState: cS } = React;

/* Departments — each carries a single hue; tint the orb with it and it becomes
   that aisle's identity (see the Orb System page in the brand book). */
const DEPTS = [
  { id: 'all',    name: 'All',    hue: null },
  { id: 'fresh',  name: 'Fresh',  hue: 135 },
  { id: 'dairy',  name: 'Dairy',  hue: 240 },
  { id: 'pantry', name: 'Pantry', hue: 55 },
  { id: 'bakery', name: 'Bakery', hue: 30 },
  { id: 'drinks', name: 'Drinks', hue: 320 },
];
const DEPT_OF = {
  'p-tom': 'fresh', 'p-bas': 'fresh', 'p-gar': 'fresh', 'p-onn': 'fresh',
  'p-chl': 'fresh', 'p-lem': 'fresh', 'p-spi': 'fresh', 'p-avo': 'fresh',
  'p-moz': 'dairy', 'p-eggs': 'dairy', 'p-milk': 'dairy', 'p-but': 'dairy',
  'p-oil': 'pantry', 'p-pas': 'pantry',
  'p-bread': 'bakery', 'p-coff': 'drinks',
  'q-flour': 'pantry', 'q-sem': 'pantry', 'q-corn': 'pantry', 'q-bp': 'pantry',
  'q-rose': 'pantry', 'q-van': 'pantry', 'q-sugar': 'pantry',
};
const deptOf = (id) => DEPTS.find((d) => d.id === DEPT_OF[id]) || DEPTS[1];

/* Editorial product detail — the "why we stock it" voice applied to a SKU. */
const DETAIL = {
  'p-tom':  { origin: 'Isle of Wight, UK',   producer: 'The Tomato Stall',  why: "Picked on the vine and never gas-ripened — they actually smell like tomato. We only list these May–September.", facts: ['18 kcal / 100g', 'high in lycopene', 'plastic-free'] },
  'p-moz':  { origin: 'Campania, Italy',      producer: 'Caseificio Vannulo', why: "DOP buffalo milk, made the morning before it ships. If it arrives more than 2 days old, we don't send it.", facts: ['cold-chain 4°C', 'DOP certified', 'vegetarian rennet'] },
  'p-oil':  { origin: 'Jaén, Andalusia',      producer: 'Casas de Hualdo',    why: "Single-estate, first cold press, harvested early for a peppery finish. The $4.50 off this week is real, not a markup-then-discount.", facts: ['0.2% acidity', 'first cold press', 'single estate'] },
  'p-pas':  { origin: 'Gragnano, Italy',       producer: 'Pastificio dei Campi', why: "Bronze-cut and slow-dried for 30 hours, so sauce actually clings to it. Worth the extra 80¢ over the supermarket box.", facts: ['bronze die', '30h slow dried', 'vegan'] },
  'p-coff': { origin: 'Huila, Colombia',       producer: 'Rosa & Sons',        why: "Roasted last Tuesday — we print the roast date, not a best-before. Bright, with a cocoa finish.", facts: ['roast date printed', 'single origin', 'washed process'] },
  'p-bread':{ origin: 'Hackney, London',       producer: 'E5 Bakehouse',       why: "Baked the same morning it reaches you, 36-hour ferment. Sells out by noon in the shop — we hold yours back.", facts: ['36h ferment', 'baked same day', 'no additives'] },
};
const detailOf = (id) => DETAIL[id] || {
  origin: 'Sourced nearby', producer: 'A Blyzr partner', why: "A quiet staff favourite — consistent, fairly priced, and it does exactly what you need it to.", facts: ['quality checked', 'fair trade terms'],
};

/* ---- Department dot (tinted orb) ---- */
const DeptDot = ({ hue, size = 16 }) => (
  <span
    className={`dept-dot ${hue == null ? 'all' : ''}`}
    style={hue == null ? { width: size, height: size } : { width: size, height: size, '--h': hue }}
  />
);

/* ---- Catalog card (branded glyph thumb, whole card opens detail) ---- */
const CatalogCard = ({ p, inBasket, onAdd, onOpen }) => {
  const d = deptOf(p.id);
  return (
    <div className="product" style={{ cursor: 'pointer' }} onClick={() => onOpen(p.id)}>
      <div className="product-thumb">
        <PThumb p={p} className="glyph"/>
        <span className="sku">{p.sku}</span>
        <span className="badge" style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <DeptDot hue={d.hue} size={9}/> {d.name}
        </span>
      </div>
      <div className="product-name">{p.name}</div>
      <div className="product-sub">{p.sub}</div>
      <div className="product-foot">
        <span className="product-price">${p.price.toFixed(2)}</span>
        <button
          className="product-add"
          style={inBasket ? { background: 'var(--accent)', color: 'var(--ink)', borderColor: 'var(--accent)' } : {}}
          onClick={(e) => { e.stopPropagation(); onAdd(p.id); }}
          aria-label="Add"
        >
          {inBasket ? <Icon.check/> : <Icon.plus/>}
        </button>
      </div>
    </div>
  );
};

/* ============================================
   CATALOG
   ============================================ */
const Catalog = ({ onOpenProduct, onAdd, basket, onSend }) => {
  const [dept, setDept] = cS('all');
  const items = BLYZR.products.filter((p) => dept === 'all' || DEPT_OF[p.id] === dept);

  return (
    <>
      <CanvasHeader
        crumb="08 — catalog"
        title="The <em>aisles.</em>"
        subtitle="Browse by department, or just ask. Every product opens to where it's from and why Blyzr decided to stock it."
        right={(
          <button className="btn btn-outline" onClick={() => onSend('what should i buy this week')}>
            <OrbMini/> Ask the aisle
          </button>
        )}
      />

      {/* Department filter */}
      <div className="dept-bar">
        {DEPTS.map((d) => (
          <button key={d.id} className={`dept-chip ${dept === d.id ? 'active' : ''}`} onClick={() => setDept(d.id)}>
            <DeptDot hue={d.hue}/> {d.name}
            <span className="mono" style={{ fontSize: 10, opacity: 0.6, marginLeft: 2 }}>
              {d.id === 'all' ? BLYZR.products.length : BLYZR.products.filter((p) => DEPT_OF[p.id] === d.id).length}
            </span>
          </button>
        ))}
      </div>

      {/* Real-image feature banner */}
      <div className="feature-banner">
        <image-slot id="cat-feature" shape="rect" placeholder="Drop a seasonal hero photo" fit="cover"></image-slot>
        <div className="fb-overlay">
          <div className="fb-eyebrow">In season · this week</div>
          <div className="fb-title">Peak <em>tomato</em>.</div>
          <div className="fb-sub">Six vine varieties at their best — Blyzr only lists them May through September.</div>
        </div>
      </div>

      <div className="sec-head">
        <h3>{DEPTS.find((d) => d.id === dept).name === 'All' ? 'Everything' : DEPTS.find((d) => d.id === dept).name}</h3>
        <span className="meta">{items.length} products</span>
      </div>

      <div className="grid-4">
        {items.map((p) => (
          <CatalogCard key={p.id} p={p} inBasket={basket.has(p.id)} onAdd={onAdd} onOpen={onOpenProduct}/>
        ))}
      </div>
    </>
  );
};

/* ============================================
   PRODUCT DETAIL — expanded images + editorial
   ============================================ */
const ProductDetail = ({ productId, onAdd, onQty, quantities, basket, onBack, onOpenProduct, onSend, onGoBasket }) => {
  const p = BLYZR.productById[productId] || BLYZR.products[0];
  const d = deptOf(p.id);
  const meta = detailOf(p.id);
  const q = quantities[p.id] || 0;
  const inBasket = basket.has(p.id);

  const related = BLYZR.products
    .filter((x) => x.id !== p.id && DEPT_OF[x.id] === DEPT_OF[p.id])
    .concat(BLYZR.products.filter((x) => x.id !== p.id && DEPT_OF[x.id] !== DEPT_OF[p.id]))
    .slice(0, 3);

  return (
    <>
      <div style={{ display: 'flex', gap: 12, marginBottom: 20 }}>
        <button className="btn btn-ghost" onClick={onBack}><Icon.back/> Catalog</button>
      </div>

      <div className="pdp">
        {/* GALLERY — real images via slots */}
        <div className="pdp-gallery">
          <div className="pdp-hero">
            <image-slot id={`pdp-${p.id}-hero`} shape="rounded" radius="20" src={p.img || undefined} placeholder={`Drop a ${p.name.toLowerCase()} photo`} fit="cover"></image-slot>
            {/* glyph watermark only shows around the empty slot edges; SKU chip floats on top */}
            <span className="pdp-sku mono">{p.sku}</span>
          </div>
          <div className="pdp-thumbs">
            {[1, 2, 3].map((n) => (
              <image-slot key={n} id={`pdp-${p.id}-${n}`} shape="rounded" radius="14" placeholder={n === 1 ? 'angle' : n === 2 ? 'detail' : 'in use'} fit="cover"></image-slot>
            ))}
          </div>
        </div>

        {/* INFO */}
        <div className="pdp-info">
          <div className="eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
            <DeptDot hue={d.hue} size={13}/> {d.name} · {meta.origin}
          </div>
          <h2 className="pdp-name">{p.name}</h2>
          <div className="pdp-sub">{p.sub}</div>

          <div className="pdp-price-row">
            <span className="pdp-price">${p.price.toFixed(2)}</span>
            {inBasket ? (
              <div className="qty" style={{ height: 36 }}>
                <button onClick={() => onQty(p.id, q - 1)}><Icon.minus/></button>
                <span className="n">{q}</span>
                <button onClick={() => onQty(p.id, q + 1)}><Icon.plus/></button>
              </div>
            ) : (
              <button className="btn btn-accent btn-lg" onClick={() => onAdd(p.id)}>
                Add to basket <Icon.plus style={{ width: 14, height: 14 }}/>
              </button>
            )}
          </div>

          {/* WHY — agent voice on a SKU */}
          <div className="pdp-why">
            <div className="eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <OrbMini/> Why Blyzr stocks this
            </div>
            <p className="pdp-why-text">{meta.why}</p>
            <button className="btn btn-ghost" style={{ padding: 0, color: 'var(--ink-3)', marginTop: 4 }} onClick={() => onSend(`tell me more about the ${p.name.toLowerCase()}`)}>
              Ask a question <Icon.arrow style={{ width: 13, height: 13 }}/>
            </button>
          </div>

          {/* META */}
          <div className="pdp-meta-list">
            <div className="pdp-meta-row"><span className="k">Producer</span><span className="v">{meta.producer}</span></div>
            <div className="pdp-meta-row"><span className="k">Origin</span><span className="v">{meta.origin}</span></div>
            <div className="pdp-meta-row"><span className="k">Good to know</span><span className="v" style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'flex-end' }}>
              {meta.facts.map((f) => <span key={f} className="fact-chip">{f}</span>)}
            </span></div>
          </div>
        </div>
      </div>

      {/* PAIRS WITH */}
      <div className="sec-head" style={{ marginTop: 44 }}>
        <h3>Pairs with</h3>
        <span className="meta">from the same kitchen</span>
      </div>
      <div className="grid-3">
        {related.map((rp) => (
          <CatalogCard key={rp.id} p={rp} inBasket={basket.has(rp.id)} onAdd={onAdd} onOpen={onOpenProduct}/>
        ))}
      </div>
    </>
  );
};

window.Catalog = Catalog;
window.ProductDetail = ProductDetail;
window.DEPTS = DEPTS;
