// PDP step — side-by-side:
//   BEFORE (BRUNT today): "You may also like" = more of the SAME boots (low diversity).
//   AFTER (Malachyte): "Complete the jobsite fit" = COMPLEMENTARY apparel that pairs
//   with the boot — pants, tops and layers, ranked for the visitor's trade.
function StepPDP({ state, setState }) {
  const persona = window.PERSONAS.find(p => p.id === state.persona) || window.PERSONAS[0];
  const favorites = state.favorites || [];

  // Anchor product: BRUNT's flagship boot — The Marin Waterproof (Comp Toe).
  const anchor =
    window.PRODUCTS.find(p => p.name === 'The Marin Waterproof (Comp Toe)') ||
    window.PRODUCTS.find(p => p.cats.includes('comp-toe') && p.cats.includes('waterproof')) ||
    window.PRODUCTS[0];

  return (
    <div className="sbs-shell">
      <div className="sbs-grid">
        <PDPColumn mode="alpha" anchor={anchor} persona={persona} favorites={favorites} />
        <PDPColumn mode="malachyte" anchor={anchor} persona={persona} favorites={favorites} />
      </div>
    </div>
  );
}

const PAIR_LABEL = { bottoms: 'Bottoms', tops: 'Top layer', outerwear: 'Outer layer' };

function PDPColumn({ mode, anchor, persona, favorites }) {
  const isMal = mode === 'malachyte';
  const favWeights = window.buildFavWeights ? window.buildFavWeights(favorites) : null;
  const handleImgErr = (e) => { e.target.src = window.PRODUCT_FALLBACK; };

  let recs;
  if (!isMal) {
    // BRUNT today: just more boots, catalog order. Same look, over and over.
    recs = window.PRODUCTS
      .filter(p => p.id !== anchor.id && p.cats.includes('boots'))
      .sort((a, b) => a.idx - b.idx)
      .slice(0, 6);
  } else {
    // Malachyte: complementary apparel — round-robin across bottoms / tops / outerwear,
    // each bucket ranked by the visitor vector, so the fit is diverse AND persona-aware.
    const buckets = ['bottoms', 'tops', 'outerwear'];
    const ranked = {};
    for (const b of buckets) {
      ranked[b] = window.rankProducts(
        window.PRODUCTS.filter(p => p.cats.includes('apparel') && p.cats.includes(b)),
        persona, favWeights
      );
    }
    recs = [];
    let bi = 0;
    while (recs.length < 6 && buckets.some(b => ranked[b].length)) {
      const b = buckets[bi % buckets.length];
      if (ranked[b].length) { const item = ranked[b].shift(); item.__pair = b; recs.push(item); }
      bi++;
    }
  }

  return (
    <div className={`sbs-col sbs-col--${mode}`}>
      <div className="sbs-col__head">
        <span className="sbs-col__tag">{isMal ? 'AFTER' : 'BEFORE'}</span>
        <img
          src={isMal ? 'assets/malachyte-logo-gradient.png' : 'assets/brunt-logo.png'}
          alt={isMal ? 'Malachyte' : 'BRUNT'}
          className={`sbs-col__logo sbs-col__logo--${isMal ? 'mal' : 'wiha'}`}
        />
        <span className="sbs-col__caption">{isMal ? 'Complementary — completes the fit' : 'More of the same boots'}</span>
      </div>

      <div className="sbs-col__viewport">
        <div className="demo-urlbar">
          <div className="demo-urlbar__dots"><span /><span /><span /></div>
          <div className="demo-urlbar__url">
            bruntworkwear.com/products/{anchor.url ? anchor.url.split('/').pop() : 'the-marin-waterproof-comp-toe'}
            {isMal ? ' · personalized by malachyte' : ''}
          </div>
        </div>

        <WihaChrome />

        <div className="wiha-plp-root">
          <div className="wiha-crumbs">
            <a>Home</a><span className="sep">/</span>
            <a>Boots</a><span className="sep">/</span>
            <span className="current">{anchor.name}</span>
          </div>

          <div className="pdp-anchor">
            <div className="pdp-anchor__img">
              <img src={anchor.img} alt={anchor.name} onError={handleImgErr} />
            </div>
            <div className="pdp-anchor__body">
              <h2 className="pdp-anchor__name">{anchor.name}</h2>
              <div className="pdp-anchor__price">${anchor.price.toFixed(2)}</div>
              {anchor.reviews > 0 && (
                <div className="pdp-anchor__rating">★★★★★ <span>{anchor.reviews.toLocaleString()} reviews</span></div>
              )}
              <p className="pdp-anchor__desc">
                Waterproof full-grain leather with a composite safety toe (ASTM-rated). BRUNT's
                plush PU footbed and slip-resistant outsole, built for 12-hour shifts on any jobsite.
              </p>
            </div>
          </div>

          <div className="pdp-recs">
            <div className="pdp-recs__head">
              {isMal ? (
                <>
                  <h3 className="pdp-recs__title">Complete The Uniform</h3>
                  <span className="sbs-toolbar__static">CROSS-CATEGORY · PANTS · TOPS · LAYERS</span>
                </>
              ) : (
                <>
                  <h3 className="pdp-recs__title">You may also like</h3>
                  <span className="sbs-toolbar__static">SAME CATEGORY · MORE BOOTS</span>
                </>
              )}
            </div>

            <div className="pdp-carousel">
              {recs.map((p, i) => (
                <a key={p.id} className="pdp-rec-mini" href="#" onClick={(e) => e.preventDefault()}>
                  <div className="pdp-rec-mini__img">
                    <img src={p.img} alt={p.name} onError={handleImgErr} />
                  </div>
                  {isMal && p.__pair && <div className="pdp-rec-mini__pair">{PAIR_LABEL[p.__pair]}</div>}
                  <div className="pdp-rec-mini__name">{p.name}</div>
                  <div className="pdp-rec-mini__price">${p.price.toFixed(2)}</div>
                  {isMal && i < 3 && <div className="pdp-rec-mini__rank">#{i + 1}</div>}
                </a>
              ))}
            </div>

            <div className={`pdp-recs__foot pdp-recs__foot--${mode}`}>
              {isMal
                ? 'One boot → a full outfit. Higher AOV, fewer dead-end product pages.'
                : 'Six near-identical boots. Nothing to add to the cart they don\u2019t already have.'}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StepPDP });
