// Hatch Merchandising Portal — live carousels + 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];

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

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

  const CRITERIA = [
    { id: 'nursing',   label: 'Nursing · Post-partum', test: p => p.cats.includes('nursing') },
    { id: 'dress',     label: 'Dresses',               test: p => p.cats.includes('dress') },
    { id: 'top',       label: 'Tops & Tanks',          test: p => p.cats.includes('top') },
    { id: 'bottom',    label: 'Bottoms & Pants',       test: p => p.cats.includes('bottom') },
    { id: 'swimwear',  label: 'Swimwear',              test: p => p.cats.includes('swimwear') },
    { id: 'sleepwear', label: 'Lounge & Sleepwear',    test: p => p.cats.includes('sleepwear') },
    { id: 'color-pop', label: 'Color & Statement',     test: p => p.cats.includes('color-pop') },
    { id: 'neutral',   label: 'Neutrals & Basics',     test: p => p.cats.includes('neutral') },
    { id: 'crochet',   label: 'Crochet & Texture',     test: p => p.cats.includes('crochet') },
    { id: 'denim',     label: 'Denim',                 test: p => p.cats.includes('denim') },
    { id: 'floral',    label: 'Floral prints',         test: p => p.cats.includes('floral') },
    { id: 'premium',   label: 'Premium ($200+)',       test: p => p.cats.includes('premium') },
    { id: 'budget',    label: 'Value (under $100)',    test: p => p.cats.includes('budget') },
    { id: 'stripe',    label: 'Stripes & Patterns',   test: p => p.cats.includes('stripe') || p.cats.includes('pattern') },
  ];
  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) || rule.strength === 0) continue;
        if (rule.type === 'boost') { score += rule.strength; effects.push({ kind: 'boost', text: `${crit.label} +${rule.strength}` }); }
        else { score -= rule.strength; effects.push({ kind: 'bury', text: `${crit.label} −${rule.strength}` }); }
      }
      return { p, score, effects };
    });
  }, [rules]);

  const dressPool    = products.filter(p => p.cats.includes('dress'));
  const topPool      = products.filter(p => p.cats.includes('top'));
  const bottomPool   = products.filter(p => p.cats.includes('bottom'));
  const swimSleepPool= products.filter(p => p.cats.includes('swimwear') || p.cats.includes('sleepwear'));

  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]?.baseScore || 0, finalScore: (base[i]?.baseScore || 0) * 10 + r.score }));
    return rerankWithPins(scored, carouselId, pins, byId, slotCount);
  }, [persona, rules, pins, applyRules, byId]);

  const dressRanked    = React.useMemo(() => buildCarousel(dressPool,    'dress',    6), [buildCarousel, dressPool]);
  const topRanked      = React.useMemo(() => buildCarousel(topPool,      'top',      6), [buildCarousel, topPool]);
  const bottomRanked   = React.useMemo(() => buildCarousel(bottomPool,   'bottom',   6), [buildCarousel, bottomPool]);
  const swimSleepRanked= React.useMemo(() => buildCarousel(swimSleepPool,'swimsleep',6), [buildCarousel, swimSleepPool]);

  const addRule = () => { setRules(prev => [...prev, { id: nextRuleId, type: 'boost', criteria: 'nursing', 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));

  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(defaultRules); setNextRuleId(2); setPins({}); };

  const trayIds = React.useMemo(() => {
    const ids = [], used = new Set();
    const buckets = ['dress','nursing','lounge','top','bottom','swimwear','floral','crochet','denim','color-pop','neutral','premium','budget','sleepwear','stripe','pattern'];
    for (const b of buckets) {
      products.filter(p => p.cats.includes(b) && !used.has(p.id)).slice(0, 2).forEach(p => { ids.push(p.id); used.add(p.id); });
    }
    products.forEach(p => { if (ids.length < 24 && !used.has(p.id)) { ids.push(p.id); used.add(p.id); } });
    return ids.slice(0, 24);
  }, [products]);

  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)}>×</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">{displayItem.p.name}</div>
        <div style={{ fontSize: 10, color: '#8C877F', marginBottom: 3 }}>{displayItem.p.color}</div>
        <div className="merch-slot__price">${displayItem.p.price.toFixed(0)}</div>
        <ScoreBar product={displayItem.p} persona={persona} effects={displayItem.effects} />
      </div>
    );
  };

  return (
    <div className="merch-root">
      <a href="https://portal.demo.malachyte.com/login/hatch" 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 Hatch merchandising portal</div>
        <span className="merch-portal-cta__arrow">↗</span>
      </a>

      <div className="merch-layout">
        <div className="merch-preview">
          <HatchCarousel title="Dresses" subtitle={`Lifestyle stage + style vector · ranked for ${persona.userId}`}>
            {dressRanked.slice(0,6).map((item,i) => renderCard(item,'dress',i))}
          </HatchCarousel>
          <HatchCarousel title="Tops & Tanks" subtitle="Style affinity + rule engine">
            {topRanked.slice(0,6).map((item,i) => renderCard(item,'top',i))}
          </HatchCarousel>
          <HatchCarousel title="Bottoms & Pants" subtitle="Outfit-builder propensity + rule engine">
            {bottomRanked.slice(0,6).map((item,i) => renderCard(item,'bottom',i))}
          </HatchCarousel>
          <HatchCarousel title="Swim & Sleep" subtitle="Lifecycle stage + comfort vector">
            {swimSleepRanked.slice(0,6).map((item,i) => renderCard(item,'swimsleep',i))}
          </HatchCarousel>
        </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}</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 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>
  );
}

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('-').pop(), 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);
    result[i] = sorted.find(s => s.p.id === id) || { p: byId[id], score: 100, finalScore: 100, baseScore: 0, effects: [] };
  });
  let ni = 0;
  for (let i = 0; i < result.length; i++) { if (!result[i] && ni < nonPinned.length) result[i] = nonPinned[ni++]; }
  return result.filter(Boolean);
}

function HatchCarousel({ 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' : 'Keep at least one'}>×</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 });
