// Step 5 — Merchandising Portal (MyGemma)
// Live New Arrivals preview across houses/categories + rule engine + pin tray.

function StepMerch({ state, setState }) {
  const products = window.PRODUCTS || [];
  const byId = React.useMemo(() => Object.fromEntries(products.map(p => [p.id, p])), [products]);
  const persona = window.PERSONAS.find(p => p.id === state.persona) || window.PERSONAS[0];

  // ===== Rules state =====
  const DEFAULT_RULE = { id: 1, type: 'boost', criteria: 'quiet-luxury', strength: 0 };
  const rules = state.merchRules && state.merchRules.length ? state.merchRules : [DEFAULT_RULE];
  const setRules = (updater) => {
    setState(s => {
      const curr = s.merchRules && s.merchRules.length ? s.merchRules : [DEFAULT_RULE];
      const next = typeof updater === 'function' ? updater(curr) : updater;
      return { ...s, merchRules: next };
    });
  };
  const [nextRuleId, setNextRuleId] = React.useState(() => {
    const max = Math.max(0, ...(state.merchRules || []).map(r => r.id));
    return max + 1;
  });

  // ===== Pins =====
  const pins = state.merchPins || {};
  const setPins = (updater) => {
    setState(s => {
      const curr = s.merchPins || {};
      const next = typeof updater === 'function' ? updater(curr) : updater;
      return { ...s, merchPins: next };
    });
  };
  const [draggingId, setDraggingId] = React.useState(null);
  const [dragOverKey, setDragOverKey] = React.useState(null);

  // ===== Criteria — luxury houses / categories / tiers =====
  const CRITERIA = [
    { id: 'hermes',        label: 'Hermès',           test: (p) => p.brandSlug === 'hermes' },
    { id: 'chanel',        label: 'Chanel',           test: (p) => p.brandSlug === 'chanel' },
    { id: 'lv',            label: 'Louis Vuitton',    test: (p) => p.brandSlug === 'lv' },
    { id: 'monogram',      label: 'Monogram · logo',  test: (p) => p.cats.includes('monogram') },
    { id: 'quiet-luxury',  label: 'Quiet luxury',     test: (p) => p.cats.includes('quiet-luxury') },
    { id: 'fine-jewelry',  label: 'Fine jewelry',     test: (p) => p.cats.includes('fine-jewelry') },
    { id: 'gold',          label: 'Gold',             test: (p) => p.cats.includes('gold') },
    { id: 'statement',     label: 'Statement · trend',test: (p) => p.cats.includes('statement') },
    { id: 'neutral-tone',  label: 'Neutral tones',    test: (p) => p.cats.includes('neutral-tone') },
    { id: 'investment',    label: 'Investment tier',  test: (p) => p.cats.includes('investment') },
    { id: 'sale',          label: 'On sale',          test: (p) => p.sale === true },
    { id: 'new',           label: 'New arrivals',     test: (p) => p.isNew === true },
    { id: 'premium',       label: 'Price ≥ $3,000',   test: (p) => (p.price || 0) >= 3000 },
    { id: 'under-1500',    label: 'Under $1,500',     test: (p) => (p.price || 0) < 1500 },
  ];
  const criteriaMap = Object.fromEntries(CRITERIA.map(c => [c.id, c]));

  const applyRules = React.useCallback((pool) => {
    return pool.map(p => {
      let score = 100;
      const effects = [];
      for (const rule of rules) {
        const crit = criteriaMap[rule.criteria];
        if (!crit || !crit.test(p)) continue;
        if (rule.strength === 0) continue;
        if (rule.type === 'boost') { score += rule.strength; effects.push({ kind: 'boost', text: `${crit.label} +${rule.strength}` }); }
        else if (rule.type === 'bury') { score -= rule.strength; effects.push({ kind: 'bury', text: `${crit.label} −${rule.strength}` }); }
      }
      return { p, score, effects };
    });
  }, [rules]);

  // ===== Pools — four carousels across MyGemma's range =====
  const handbagPool  = products.filter(p => p.cats[0] === 'bag');
  const jewelryPool  = products.filter(p => p.cats[0] === 'jewelry');
  const slgPool      = products.filter(p => p.cats[0] === 'slg' || p.cats[0] === 'accessory' || p.cats[0] === 'watch');
  const statementPool = products.filter(p => p.cats.includes('statement') || p.cats.includes('monogram') || p.cats.includes('bright-tone'));

  const buildCarousel = React.useCallback((pool, carouselId, slotCount = 6) => {
    const base = pool.map(p => ({ p, baseScore: window.scoreFor(p, persona, null) }))
      .sort((a, b) => b.baseScore - a.baseScore);
    const scored = applyRules(base.map(x => x.p)).map((r, i) => ({
      ...r,
      baseScore: base[i] ? base[i].baseScore : 0,
      finalScore: (base[i]?.baseScore || 0) * 10 + r.score,
    }));
    return rerankWithPins(scored, carouselId, pins, byId, slotCount);
  }, [persona, rules, pins, applyRules, byId]);

  const handbagRanked   = React.useMemo(() => buildCarousel(handbagPool,   'handbag',   6), [buildCarousel, handbagPool]);
  const jewelryRanked   = React.useMemo(() => buildCarousel(jewelryPool,   'jewelry',   6), [buildCarousel, jewelryPool]);
  const slgRanked       = React.useMemo(() => buildCarousel(slgPool,       'slg',       6), [buildCarousel, slgPool]);
  const statementRanked = React.useMemo(() => buildCarousel(statementPool, 'statement', 6), [buildCarousel, statementPool]);

  // ===== Rule manipulation =====
  const addRule = () => { setRules(prev => [...prev, { id: nextRuleId, type: 'boost', criteria: 'fine-jewelry', strength: 30 }]); setNextRuleId(n => n + 1); };
  const updateRule = (id, patch) => setRules(prev => prev.map(r => r.id === id ? { ...r, ...patch } : r));
  const deleteRule = (id) => setRules(prev => prev.filter(r => r.id !== id));

  // ===== Pin manipulation =====
  const handleDragStart = (id) => (e) => { setDraggingId(id); e.dataTransfer.effectAllowed = 'move'; try { e.dataTransfer.setData('text/plain', id); } catch {} };
  const handleDragEnd = () => { setDraggingId(null); setDragOverKey(null); };
  const handleSlotDragOver = (key) => (e) => { e.preventDefault(); setDragOverKey(key); };
  const handleSlotDragLeave = () => setDragOverKey(null);
  const handleSlotDrop = (key) => (e) => {
    e.preventDefault();
    const id = draggingId || e.dataTransfer.getData('text/plain');
    if (!id) return;
    setPins(prev => { const next = { ...prev }; for (const k of Object.keys(next)) if (next[k] === id) delete next[k]; next[key] = id; return next; });
    setDraggingId(null); setDragOverKey(null);
  };
  const clearPin = (key) => setPins(prev => { const n = { ...prev }; delete n[key]; return n; });

  const resetAll = () => { setRules([DEFAULT_RULE]); setNextRuleId(2); setPins({}); };

  // ===== Pin tray =====
  const trayIds = React.useMemo(() => {
    const ids = []; const used = new Set();
    const buckets = ['hermes', 'chanel', 'lv', 'gucci', 'cartier', 'tiffany', 'vca', 'david-yurman', 'dior', 'bottega', 'jewelry', 'bag', 'slg', 'accessory', 'gold', 'statement'];
    for (const b of buckets) {
      const matching = products.filter(p => p.cats.includes(b) && !used.has(p.id)).slice(0, 2);
      for (const p of matching) { ids.push(p.id); used.add(p.id); }
    }
    for (const p of products) { if (ids.length >= 24) break; if (!used.has(p.id)) { ids.push(p.id); used.add(p.id); } }
    return ids.slice(0, 24);
  }, [products]);

  // ===== Card renderer =====
  const renderCard = (item, carouselId, index) => {
    const slotKey = `${carouselId}-${index}`;
    const pinnedId = pins[slotKey];
    const displayItem = pinnedId ? { ...item, p: byId[pinnedId], pinned: true, effects: item.effects || [] } : item;
    const isDragOver = dragOverKey === slotKey;
    if (!displayItem.p) return null;
    return (
      <div
        key={slotKey}
        className={`merch-slot ${isDragOver ? 'is-drag-over' : ''} ${pinnedId ? 'is-pinned' : ''}`}
        onDragOver={handleSlotDragOver(slotKey)} onDragLeave={handleSlotDragLeave} onDrop={handleSlotDrop(slotKey)}
      >
        {pinnedId && (<><div className="merch-slot__pin-badge">📌 PINNED</div><button className="merch-slot__unpin" onClick={() => clearPin(slotKey)} title="Remove pin">×</button></>)}
        <div className="merch-slot__rank">#{index + 1}</div>
        <div className="merch-slot__img">
          <img src={displayItem.p.img} alt={displayItem.p.name} onError={(e) => { e.target.src = window.PRODUCT_FALLBACK; }} />
        </div>
        <div className="merch-slot__name"><span className="merch-slot__brand">{displayItem.p.brand}</span>{displayItem.p.name}</div>
        <div className="merch-slot__price">${displayItem.p.price.toLocaleString()}</div>
        <ScoreBar product={displayItem.p} persona={persona} effects={displayItem.effects} />
      </div>
    );
  };

  return (
    <div className="merch-root">
      <a href="https://portal.demo.malachyte.com/login/mygemma" target="_blank" rel="noopener noreferrer" className="merch-portal-cta merch-portal-cta--top">
        <div className="merch-portal-cta__bg" aria-hidden="true">
          <span className="merch-portal-cta__oval merch-portal-cta__oval--1" />
          <span className="merch-portal-cta__oval merch-portal-cta__oval--2" />
        </div>
        <img src="assets/malachyte-logo-gradient.png" alt="Malachyte" className="merch-portal-cta__logo" />
        <div className="merch-portal-cta__title">Open the full MyGemma merchandising portal</div>
        <span className="merch-portal-cta__arrow">↗</span>
      </a>

      <div className="merch-layout">
        <div className="merch-preview">
          <Carousel title="Handbags" subtitle={`Persona vector + rule engine · ranked for ${persona.userId}`}>
            {handbagRanked.slice(0, 6).map((item, i) => renderCard(item, 'handbag', i))}
          </Carousel>
          <Carousel title="Fine Jewelry" subtitle="Maison + material affinity + rule engine">
            {jewelryRanked.slice(0, 6).map((item, i) => renderCard(item, 'jewelry', i))}
          </Carousel>
          <Carousel title="Small Leather & Accessories" subtitle="Everyday pairing + rule engine">
            {slgRanked.slice(0, 6).map((item, i) => renderCard(item, 'slg', i))}
          </Carousel>
          <Carousel title="Statement & Monogram" subtitle="Trend propensity + rule engine">
            {statementRanked.slice(0, 6).map((item, i) => renderCard(item, 'statement', i))}
          </Carousel>
        </div>

        <div className="merch-panel">
          <div className="merch-panel__head">
            <div className="merch-panel__brand">
              <img src="assets/malachyte-symbol-gradient.png" alt="Malachyte" className="merch-panel__logo" />
              <div>
                <div className="merch-panel__eyebrow">MALACHYTE</div>
                <div className="merch-panel__title">Merchandising Controls</div>
              </div>
            </div>
            <button className="merch-reset" onClick={resetAll}>↻ Reset</button>
          </div>

          <div className="merch-persona-row">
            <div className="merch-persona-row__text">
              <div className="merch-persona-row__lbl">ACTIVE VISITOR</div>
              <div className="merch-persona-row__name">{persona.userId} · {persona.name.split('·')[0].trim()}</div>
            </div>
          </div>

          <div className="merch-rules">
            <div className="merch-rules__head">
              <span>Boost / Bury rules</span>
              <span className="merch-rules__hint">Layered on persona vector</span>
            </div>
            {rules.map(rule => (
              <RuleRow key={rule.id} rule={rule} criteria={CRITERIA} onUpdate={(patch) => updateRule(rule.id, patch)} onDelete={() => deleteRule(rule.id)} canDelete={rules.length > 1} />
            ))}
            <button className="merch-add-rule" onClick={addRule}>+ Add rule</button>
          </div>

          <div className="merch-pin-tray">
            <div className="merch-pin-tray__head">
              <div className="merch-pin-tray__title">Pin products to slots</div>
              <div className="merch-pin-tray__sub">Drag any product onto any slot in any carousel</div>
            </div>
            <div className="merch-pin-grid">
              {trayIds.map(id => {
                const p = byId[id];
                if (!p) return null;
                const isPinned = Object.values(pins).includes(id);
                return (
                  <div key={id} className={`merch-pin-prod ${isPinned ? 'is-pinned' : ''} ${draggingId === id ? 'is-dragging' : ''}`}
                    draggable={!isPinned} onDragStart={handleDragStart(id)} onDragEnd={handleDragEnd}
                    title={isPinned ? `${p.name} already pinned` : `Drag ${p.name} to pin`}>
                    <img src={p.img} alt={p.name} onError={(e) => { e.target.src = window.PRODUCT_FALLBACK; }} />
                    {isPinned && <span className="merch-pin-prod__mark">📌</span>}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// Helpers
// ============================================================================
function rerankWithPins(scored, carouselId, pins, byId, slotCount) {
  const sorted = [...scored].sort((a, b) => (b.finalScore ?? b.score) - (a.finalScore ?? a.score));
  const carouselPins = {};
  Object.keys(pins).forEach(k => { if (k.startsWith(carouselId + '-')) { const idx = parseInt(k.split('-')[1], 10); carouselPins[idx] = pins[k]; } });
  const pinnedIds = new Set(Object.values(carouselPins));
  const nonPinned = sorted.filter(s => !pinnedIds.has(s.p.id));
  const size = Math.max(slotCount, ...Object.keys(carouselPins).map(i => parseInt(i, 10) + 1));
  const result = new Array(size).fill(null);
  Object.entries(carouselPins).forEach(([idx, id]) => {
    const i = parseInt(idx, 10);
    const existing = sorted.find(s => s.p.id === id);
    result[i] = existing || { p: byId[id], score: 100, finalScore: 100, baseScore: 0, effects: [] };
  });
  let ni = 0;
  for (let i = 0; i < result.length; i++) { if (result[i]) continue; if (ni < nonPinned.length) result[i] = nonPinned[ni++]; }
  return result.filter(Boolean);
}

function Carousel({ title, subtitle, children }) {
  return (
    <div className="merch-carousel">
      <div className="merch-carousel__head">
        <h3 className="merch-carousel__title">{title}</h3>
        <div className="merch-carousel__sub">{subtitle}</div>
      </div>
      <div className="merch-carousel__track">{children}</div>
    </div>
  );
}

function ScoreBar({ product, persona, effects }) {
  if (!product) return null;
  const score = window.relevanceScore(product, persona, null);
  return (
    <div className="merch-score">
      <div className="merch-score__val"><span className="merch-score__dot" />Score · {score.toFixed(2)}</div>
      {effects && effects.length > 0 && (
        <div className="merch-score__effects">
          {effects.map((e, i) => (<div key={i} className={`merch-effect merch-effect--${e.kind}`}>{e.text}</div>))}
        </div>
      )}
    </div>
  );
}

function RuleRow({ rule, criteria, onUpdate, onDelete, canDelete }) {
  return (
    <div className={`merch-rule merch-rule--${rule.type}`}>
      <div className="merch-rule__row">
        <select className="merch-rule__type" value={rule.type} onChange={e => onUpdate({ type: e.target.value })}>
          <option value="boost">Boost</option>
          <option value="bury">Bury</option>
        </select>
        <select className="merch-rule__crit" value={rule.criteria} onChange={e => onUpdate({ criteria: e.target.value })}>
          {criteria.map(c => (<option key={c.id} value={c.id}>{c.label}</option>))}
        </select>
        <button className="merch-rule__delete" onClick={onDelete} disabled={!canDelete} title={canDelete ? 'Remove rule' : 'Keep at least one rule'}>×</button>
      </div>
      <div className="merch-rule__slider-wrap">
        <input type="range" min={0} max={200} step={5} value={rule.strength} onChange={e => onUpdate({ strength: Number(e.target.value) })} className="merch-rule__slider" />
        <div className="merch-rule__strength">{rule.strength}</div>
      </div>
    </div>
  );
}

Object.assign(window, { StepMerch });
