// Step 5 — Merchandising Portal (90 Degree by Reflex)
// Live New-In / Best Sellers preview + rule engine + pin tray.

function StepMerch({ state, setState }) {
  const allProducts = window.PRODUCTS || [];
  const persona = window.PERSONAS.find(p => p.id === state.persona) || window.PERSONAS[0];
  // Lock the entire merchandising surface to the visitor's gender — the
  // merchandiser is previewing how the homepage will look for this shopper.
  const products = React.useMemo(
    () => allProducts.filter(p => p.gender === persona.gender),
    [allProducts, persona.gender]
  );
  const byId = React.useMemo(
    () => Object.fromEntries(products.map(p => [p.id, p])),
    [products]
  );

  // ===== Rules state =====
  const rules = state.merchRules && state.merchRules.length
    ? state.merchRules
    : [{ id: 1, type: 'boost', criteria: 'butter', strength: 0 }];
  const setRules = (updater) => {
    setState(s => {
      const curr = s.merchRules && s.merchRules.length
        ? s.merchRules
        : [{ id: 1, type: 'boost', criteria: 'butter', strength: 0 }];
      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 — apparel flavored =====
  const CRITERIA = [
    { id: 'butter',      label: 'Butter / Lux fabric', test: (p) => p.cats.includes('butter') || p.cats.includes('lux') },
    { id: 'lightstreme', label: 'Lightstreme / performance', test: (p) => p.cats.includes('lightstreme') || p.cats.includes('performance') },
    { id: 'studio',      label: 'Studio · pilates · yoga',   test: (p) => p.cats.includes('studio') },
    { id: 'run',         label: 'Run · train',               test: (p) => p.cats.includes('run') },
    { id: 'lounge',      label: 'Lounge · travel',           test: (p) => p.cats.includes('lounge') || p.cats.includes('travel') },
    { id: 'set',         label: 'Matching sets',             test: (p) => p.cats.includes('set') },
    { id: 'seamless',    label: 'Seamless',                  test: (p) => p.cats.includes('seamless') },
    { id: 'cozy',        label: 'Cozy · plush · fleece',     test: (p) => p.cats.includes('cozy') },
    { id: 'sale',        label: 'On sale',                   test: (p) => p.sale === true },
    { id: 'new',         label: 'New-In',                    test: (p) => p.isNew === true || p.cats.includes('new-in-plp') },
    { id: 'under-25',    label: 'Under $25',                 test: (p) => (p.price || 0) < 25 },
    { id: '70-plus',     label: 'Price ≥ $70',               test: (p) => (p.price || 0) >= 70 },
  ];
  const criteriaMap = Object.fromEntries(CRITERIA.map(c => [c.id, c]));

  // ===== Apply rules =====
  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 mapped to apparel) =====
  const topsPool = products.filter(p =>
    p.cats.includes('tank') || p.cats.includes('bra') || p.cats.includes('tee') ||
    p.cats.includes('long-sleeve') || p.cats.includes('top') || p.cats.includes('shirt')
  );
  const bottomsPool = products.filter(p =>
    p.cats.includes('legging') || p.cats.includes('short') ||
    p.cats.includes('pant') || p.cats.includes('skort') || p.cats.includes('jogger')
  );
  const setsPool = products.filter(p =>
    p.cats.includes('set') || p.cats.includes('romper')
  );
  const outerPool = products.filter(p =>
    p.cats.includes('hoodie') || p.cats.includes('jacket') || p.cats.includes('cozy')
  );

  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 topsRanked    = React.useMemo(() => buildCarousel(topsPool,    'tops',    6), [buildCarousel, topsPool]);
  const bottomsRanked = React.useMemo(() => buildCarousel(bottomsPool, 'bottoms', 6), [buildCarousel, bottomsPool]);
  const setsRanked    = React.useMemo(() => buildCarousel(setsPool,    'sets',    6), [buildCarousel, setsPool]);
  const outerRanked   = React.useMemo(() => buildCarousel(outerPool,   'outer',   6), [buildCarousel, outerPool]);

  // ===== Rule manipulation =====
  const addRule = () => {
    setRules(prev => [...prev, { id: nextRuleId, type: 'boost', criteria: 'butter', 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([{ id: 1, type: 'boost', criteria: 'butter', strength: 0 }]);
    setNextRuleId(2);
    setPins({});
  };

  // ===== Pin tray =====
  const trayIds = React.useMemo(() => {
    const ids = [];
    const buckets = ['butter', 'lux', 'lightstreme', 'seamless', 'set', 'legging', 'short', 'bra', 'tank', 'tee', 'jogger', 'pant', 'hoodie', 'cozy'];
    const used = new Set();
    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">{displayItem.p.name}</div>
        <div className="merch-slot__price">${displayItem.p.price.toFixed(2)}</div>

        <ScoreBar
          product={displayItem.p}
          persona={persona}
          effects={displayItem.effects}
        />
      </div>
    );
  };

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

      <div className="merch-layout">
        <div className="merch-preview">
          <Carousel
            title="Tops · Tanks · Bras"
            subtitle={`Persona vector + rule engine · ranked for ${persona.userId}`}
          >
            {topsRanked.slice(0, 6).map((item, i) => renderCard(item, 'tops', i))}
          </Carousel>

          <Carousel
            title="Bottoms · Leggings · Shorts"
            subtitle="Category-affinity + rule engine"
          >
            {bottomsRanked.slice(0, 6).map((item, i) => renderCard(item, 'bottoms', i))}
          </Carousel>

          <Carousel
            title="Matching sets"
            subtitle="Bundle propensity + rule engine"
          >
            {setsRanked.slice(0, 6).map((item, i) => renderCard(item, 'sets', i))}
          </Carousel>

          <Carousel
            title="Outerwear · cozy"
            subtitle="Lounge-vector + rule engine"
          >
            {outerRanked.slice(0, 6).map((item, i) => renderCard(item, 'outer', 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]}</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>
  );
}

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 });
