// Step 5 — Merchandising Portal (Wiha)
// Live New Tools / Best Sellers preview + rule engine + pin tray.
// Adapted from the Cookware Co. template, retuned for Wiha's catalog.

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 — persisted in state =====
  const rules = state.merchRules && state.merchRules.length
    ? state.merchRules
    : [{ id: 1, type: 'boost', criteria: 'insulated', strength: 0 }];
  const setRules = (updater) => {
    setState(s => {
      const curr = s.merchRules && s.merchRules.length
        ? s.merchRules
        : [{ id: 1, type: 'boost', criteria: 'insulated', 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: map of "carousel-slotIndex" -> productId =====
  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 definitions — Wiha-flavored =====
  const CRITERIA = [
    { id: 'insulated',   label: 'Insulated · VDE',       test: (p) => p.cats.includes('insulated') },
    { id: 'torque',      label: 'Torque control',        test: (p) => p.cats.includes('torque') },
    { id: 'color-coded', label: 'Color-coded',           test: (p) => p.cats.includes('color-coded') },
    { id: 'impact',      label: 'Impact-rated',          test: (p) => p.cats.includes('impact') },
    { id: 'precision',   label: 'Precision (PicoFinish)', test: (p) => p.cats.includes('precision') },
    { id: 'edc',         label: 'EDC · pocket',          test: (p) => p.cats.includes('edc') },
    { id: 'heavy-duty',  label: 'Heavy duty',            test: (p) => p.cats.includes('heavy-duty') },
    { id: 'go-system',   label: 'GoBox · GoStack',       test: (p) => p.cats.includes('go-system') },
    { id: 'softfinish',  label: 'SoftFinish grip',       test: (p) => p.cats.includes('softfinish') },
    { id: 'slimline',    label: 'SlimLine system',       test: (p) => p.cats.includes('slimline') },
    { id: 'sale',        label: 'On sale',               test: (p) => p.sale === true },
    { id: 'new',         label: 'New arrivals',          test: (p) => p.isNew === true || p.cats.includes('new-tools-plp') },
    { id: 'price-300',   label: 'Price ≥ $300',          test: (p) => (p.price || 0) >= 300 },
    { id: 'under-30',    label: 'Under $30',             test: (p) => (p.price || 0) < 30 },
  ];
  const criteriaMap = Object.fromEntries(CRITERIA.map(c => [c.id, c]));

  // ===== Apply rules to a candidate list =====
  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 covering Wiha's range) =====
  const screwdriverPool = products.filter(p =>
    p.cats.includes('screwdriver') || p.cats.includes('multi-driver') || p.cats.includes('blade')
  );
  const bitPool = products.filter(p =>
    p.cats.includes('bit') || p.cats.includes('nut-driver') || p.cats.includes('adapter')
  );
  const torquePool = products.filter(p =>
    p.cats.includes('torque') || p.cats.includes('wrench') || p.cats.includes('socket') || p.cats.includes('ratchet')
  );
  const kitPool = products.filter(p =>
    p.cats.includes('kit') || p.cats.includes('storage') || p.cats.includes('workstation') ||
    p.cats.includes('t-handle') || p.cats.includes('l-key') || p.cats.includes('mallet')
  );

  // ===== Carousel rankings: persona-anchored base + rule layer =====
  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 screwdriverRanked = React.useMemo(() => buildCarousel(screwdriverPool, 'screwdriver', 6), [buildCarousel, screwdriverPool]);
  const bitRanked         = React.useMemo(() => buildCarousel(bitPool,         'bit',         6), [buildCarousel, bitPool]);
  const torqueRanked      = React.useMemo(() => buildCarousel(torquePool,      'torque',      6), [buildCarousel, torquePool]);
  const kitRanked         = React.useMemo(() => buildCarousel(kitPool,         'kit',         6), [buildCarousel, kitPool]);

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

  // ===== Pin tray: hand-picked Wiha products =====
  const trayIds = React.useMemo(() => {
    const ids = [];
    const buckets = ['insulated', 'torque', 'edc', 'precision', 'go-system', 'color-coded', 'screwdriver', 'bit', 'nut-driver', 'wrench', 'socket', 't-handle', 'l-key', 'storage', 'kit'];
    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/wiha"
        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 Wiha merchandising portal
        </div>
        <span className="merch-portal-cta__arrow">↗</span>
      </a>

      <div className="merch-layout">
        {/* ============ MAIN — preview ============ */}
        <div className="merch-preview">
          <Carousel
            title="Screwdrivers"
            subtitle={`Persona vector + rule engine · ranked for ${persona.userId}`}
          >
            {screwdriverRanked.slice(0, 6).map((item, i) => renderCard(item, 'screwdriver', i))}
          </Carousel>

          <Carousel
            title="Bits & Nut Setters"
            subtitle="Drive-type affinity + rule engine"
          >
            {bitRanked.slice(0, 6).map((item, i) => renderCard(item, 'bit', i))}
          </Carousel>

          <Carousel
            title="Wrenches, Torque & Sockets"
            subtitle="Trade-vector + rule engine"
          >
            {torqueRanked.slice(0, 6).map((item, i) => renderCard(item, 'torque', i))}
          </Carousel>

          <Carousel
            title="Kits & Storage"
            subtitle="Bundle propensity + rule engine"
          >
            {kitRanked.slice(0, 6).map((item, i) => renderCard(item, 'kit', i))}
          </Carousel>
        </div>

        {/* ============ RULES PANEL (sticky right) ============ */}
        <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>

          {/* Rules list */}
          <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>

          {/* Pin tray */}
          <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 });
