// PDP step — side-by-side: "more of the same" recs vs complementary, pairs-well recs.
function StepPDP({ state, setState }) {
  const persona = window.PERSONAS.find(p => p.id === state.persona) || window.PERSONAS[0];
  const favorites = state.favorites || [];

  // Anchor: a flagship best seller — Paula wool flatweave in a coastal blue.
  const anchor =
    window.PRODUCTS.find(p => p.name === 'Paula' && p.fam === 'blue') ||
    window.PRODUCTS.find(p => p.cats.includes('bestseller-plp')) ||
    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>
  );
}

function descFor(p) {
  const base = `Hand-finished ${p.type.toLowerCase()} rug in ${p.color}, made to your exact room measurements.`;
  if (p.cats.includes('performance')) return base + ' Spill-proof, machine-washable and built for high-traffic, pet-and-kid homes.';
  if (p.cats.includes('natural-fiber')) return base + ' Durable plant fibers with a warm, organic texture underfoot.';
  if (p.cats.includes('indoor-outdoor')) return base + ' UV- and weather-resistant, equally at home on the patio or in the den.';
  return base + ' A dense, low-shed pile with a soft hand and a tailored finished edge.';
}

// "More of the same" — same construction, by price.
function sameTypeRecs(anchor) {
  let recs = window.PRODUCTS.filter(p => p.id !== anchor.id && p.type === anchor.type);
  if (recs.length < 6) {
    const pad = window.PRODUCTS.filter(p => p.id !== anchor.id && p.type !== anchor.type && p.fam === anchor.fam);
    recs = recs.concat(pad);
  }
  return [...recs].sort((a, b) => a.price - b.price).slice(0, 6);
}

// Complementary — palette-coordinated, but maximize construction/room diversity, persona-aware.
function complementRecs(anchor, persona, favWeights) {
  const harmony = window.PALETTE_HARMONY[anchor.fam] || ['neutral'];
  const scored = window.PRODUCTS
    .filter(p => p.name !== anchor.name)
    .map(p => {
      let s = window.scoreFor(p, persona, favWeights) * 0.5;
      if (harmony.includes(p.fam)) s += 1.3;
      if (p.type !== anchor.type) s += 1.1; else s -= 1.6;
      if (p.cats.includes('indoor-outdoor')) s += 0.35; // patio / mudroom continuity
      if (p.cats.includes('natural-fiber')) s += 0.25;  // texture contrast
      return { p, s };
    })
    .sort((a, b) => b.s - a.s);

  const picked = [];
  const types = new Set();
  for (const { p } of scored) {
    if (picked.length >= 6) break;
    if (!types.has(p.type)) { picked.push(p); types.add(p.type); }
  }
  for (const { p } of scored) {
    if (picked.length >= 6) break;
    if (!picked.includes(p)) picked.push(p);
  }
  return picked.slice(0, 6);
}

function diversityOf(list) {
  return {
    types: new Set(list.map(p => p.type)).size,
    palettes: new Set(list.map(p => p.fam)).size,
  };
}

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

  const recs = isMal ? complementRecs(anchor, persona, favWeights) : sameTypeRecs(anchor);
  const div = diversityOf(recs);

  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/ernesta-logo.png'}
          alt={isMal ? 'Malachyte' : 'Ernesta'}
          className={`sbs-col__logo sbs-col__logo--${isMal ? 'mal' : 'wiha'}`}
        />
        <span className="sbs-col__caption">{isMal ? 'Complementary pairings' : 'Static recommendations'}</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">
            ernestarugs.com/products/{anchor.url ? anchor.url.split('/').pop().split('?')[0] : 'paula-wool-flatweave-rug'}
            {isMal ? ' · personalized by malachyte' : ''}
          </div>
        </div>

        <ErnestaChrome />

        <div className="wiha-plp-root">
          <div className="wiha-crumbs">
            <a>Home</a><span className="sep">/</span>
            <a>Wool Rugs</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__color">
                <span className="wiha-swatch" style={{ background: anchor.famHex, display: 'inline-block', verticalAlign: 'middle', marginRight: 6 }} />
                {anchor.color} · {anchor.type}
              </div>
              <div className="pdp-anchor__price">${anchor.price.toFixed(0)}</div>
              <p className="pdp-anchor__desc">{descFor(anchor)}</p>
            </div>
          </div>

          <div className="pdp-recs">
            <div className="pdp-recs__head">
              {isMal ? (
                <h3 className="pdp-recs__title">Pairs well in your home — layered for {persona.name.toLowerCase()}</h3>
              ) : (
                <h3 className="pdp-recs__title">You may also like</h3>
              )}
              <span className={`pdp-diversity ${isMal ? 'pdp-diversity--high' : 'pdp-diversity--low'}`}>
                {isMal
                  ? `${div.types} constructions · ${div.palettes} coordinated tones`
                  : `${div.types} construction · same aisle`}
              </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>
                  <div className="pdp-rec-mini__type">{p.type}</div>
                  <div className="pdp-rec-mini__name">{p.name} · {p.color}</div>
                  <div className="pdp-rec-mini__price">${p.price.toFixed(0)}</div>
                  {isMal && i < 3 && <div className="pdp-rec-mini__rank">#{i + 1}</div>}
                </a>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StepPDP });
