// Ibex Shop All PLP — side-by-side: Ibex today (default order) vs With Malachyte (personalized).
// The visitor's gender routes them to the men's or women's Shop All catalog; both columns
// show that same gendered pool. BEFORE = static order, AFTER = ranked by visitor vector.

// =========================================================================
// Top-level: side-by-side comparison
// =========================================================================
function SideBySidePLP({ state, setState }) {
  const persona = window.PERSONAS.find(p => p.id === state.persona) || window.PERSONAS[0];
  const favorites = state.favorites || [];

  const switchPersona = (id) => setState(s => ({ ...s, persona: id, favorites: [] }));

  const toggleFav = (id) => {
    setState(s => {
      const favs = s.favorites || [];
      const next = favs.includes(id) ? favs.filter(x => x !== id) : [...favs, id];
      return { ...s, favorites: next };
    });
  };

  return (
    <div className="sbs-shell">
      <PersonaBar persona={persona} onChange={switchPersona} favoriteCount={favorites.length} />

      <div className="sbs-grid">
        <PLPColumn mode="alpha" state={state} persona={persona} favorites={favorites} onFav={toggleFav} />
        <PLPColumn mode="malachyte" state={state} persona={persona} favorites={favorites} onFav={toggleFav} />
      </div>
    </div>
  );
}

// =========================================================================
// One side of the side-by-side
// =========================================================================
function PLPColumn({ mode, state, persona, favorites, onFav }) {
  // Gender-routed Shop All pool: men's visitor → men's catalog, women's → women's.
  const genderPool = window.PRODUCTS.filter(p => p.gender === persona.gender);
  const favWeights = window.buildFavWeights ? window.buildFavWeights(favorites) : null;
  const ranked = mode === 'malachyte'
    ? window.rankProducts(genderPool, persona, favWeights)
    : window.defaultOrder(genderPool);

  const handleImgErr = (e) => { e.target.src = window.PRODUCT_FALLBACK; };
  const isMal = mode === 'malachyte';
  const collection = persona.gender === 'Men' ? 'mens' : 'womens';
  const titleGender = persona.gender === 'Men' ? 'Men' : 'Women';

  return (
    <div className={`sbs-col sbs-col--${mode}`}>
      <div className="sbs-col__head">
        <span className="sbs-col__tag">{isMal ? 'AFTER' : 'BEFORE'}</span>
        {isMal
          ? <img src="assets/malachyte-logo-gradient.png" alt="Malachyte" className="sbs-col__logo sbs-col__logo--mal" />
          : <span className="sbs-col__logo sbs-col__logo--ibex"><img src="assets/ibex-logo.png" alt="Ibex" /><b>ibex</b></span>}
        <span className="sbs-col__caption">{isMal ? 'With Malachyte' : 'Ibex today'}</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">
            ibex.com/collections/{collection}{isMal ? ' · personalized by malachyte' : ''}
          </div>
        </div>

        <WihaChrome />

        <div className="wiha-plp-root">
          <div className="wiha-crumbs">
            <a>Home</a><span className="sep">/</span><span className="current">Shop All {titleGender}</span>
          </div>

          <h1 className="wiha-plp-title">Shop All {titleGender}</h1>

          <div className="sbs-toolbar">
            <span className="sbs-toolbar__count">{ranked.length} products</span>
          </div>

          <div className={`wiha-grid-wrap wiha-grid-wrap--${mode}`}>
            <div className="wiha-grid-railbar">
              <span className="wiha-grid-railbar__dot" />
              {isMal
                ? <>PERSONALIZED · RANKED FOR <b>{persona.userId}</b></>
                : <>STATIC · SAME ORDER · NO RE-RANKING ON FAVORITES</>}
            </div>
            <div className="wiha-grid sbs-grid-inner">
              {ranked.map((p, i) => (
                <ProductCard
                  key={p.id}
                  product={p}
                  index={i}
                  mode={mode}
                  persona={persona}
                  favWeights={favWeights}
                  isFav={favorites.includes(p.id)}
                  onFav={onFav}
                  onImgErr={handleImgErr}
                />
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// =========================================================================
// Product card
// =========================================================================
function ProductCard({ product, index, mode, persona, favWeights, isFav, onFav, onImgErr }) {
  const isMal = mode === 'malachyte';
  const showRank = isMal && index < 8;

  return (
    <div className={`wiha-card ${showRank ? 'is-ranked' : ''}`}>
      {showRank && <div className="wiha-rank">#{index + 1}</div>}
      {product.sale && <div className="wiha-flag wiha-flag--sale">Sale</div>}
      {!product.sale && product.isNew && <div className="wiha-flag wiha-flag--new">New</div>}

      {isMal && (
        <button
          className={`wiha-fav ${isFav ? 'wiha-fav--on' : ''}`}
          onClick={(e) => { e.preventDefault(); onFav(product.id); }}
          aria-label={isFav ? 'Remove favorite' : 'Add favorite'}
        >
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path d="M12 21s-7.5-4.5-9.5-9.2C1 8.4 3 5 6.4 5c2 0 3.4 1.1 4.4 2.5l1.2 1.6 1.2-1.6C14.2 6.1 15.6 5 17.6 5 21 5 23 8.4 21.5 11.8 19.5 16.5 12 21 12 21z"
              fill={isFav ? '#038362' : 'none'} stroke={isFav ? '#038362' : '#2A363D'} strokeWidth="1.6" strokeLinejoin="round" />
          </svg>
        </button>
      )}

      <div className="wiha-card__img">
        <img src={product.img} alt={product.name} onError={onImgErr} loading="lazy" />
      </div>

      <div className="wiha-card__type">{product.type}</div>
      <h3 className="wiha-card__name">{product.name}</h3>

      {isMal && showRank && (() => {
        const r = reasonFor(product, persona, favWeights);
        return r ? <div className={`wiha-why wiha-why--${r.kind}`}>{r.text}</div> : null;
      })()}

      <div className="wiha-card__price-row">
        <div>
          <span className="wiha-card__price">${product.price.toFixed(2)}</span>
          {product.orig && <span className="wiha-card__orig">${product.orig.toFixed(2)}</span>}
        </div>
        <span className="wiha-card__meta">
          {product.colors > 1 ? `${product.colors} colors` : '1 color'}
          {product.reviews ? ` · ${product.reviews}★` : ''}
        </span>
      </div>
    </div>
  );
}

// =========================================================================
// Persona bar — compact, sits above both columns
// =========================================================================
function PersonaBar({ persona, onChange, favoriteCount }) {
  const [scrolled, setScrolled] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 220);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <>
      <div className="wiha-persona-bar">
        <div className="wiha-persona-bar__id">
          <span className="wiha-persona-eye">Visitor · {persona.gender}</span>
          <span className="wiha-persona-userid">{persona.userId}</span>
          {favoriteCount > 0 && (
            <span className="wiha-rank-chip" style={{ marginTop: 6 }}>
              <span className="wiha-rank-chip__dot" />
              {favoriteCount} ♥ → re-ranking
            </span>
          )}
        </div>

        <PortraitWithSignals persona={persona} />

        <div className="wiha-persona-bar__switch">
          <label>switch visitor</label>
          <select className="wiha-persona-bar__select" value={persona.id} onChange={(e) => onChange(e.target.value)}>
            {window.PERSONAS.map(p => (
              <option key={p.id} value={p.id}>{p.userId} · {p.gender}</option>
            ))}
          </select>
        </div>
      </div>

      <div className={`wiha-persona-pill ${scrolled ? 'is-visible' : ''}`}>
        <div className="wiha-persona-pill__avatar">
          <img src={persona.img} alt={persona.name} />
        </div>
        <div className="wiha-persona-pill__meta">
          <span className="wiha-persona-pill__eye">Visitor · {persona.gender}</span>
          <span className="wiha-persona-pill__id">{persona.userId}</span>
        </div>
        <div className="wiha-persona-pill__chips">
          {(persona.signals || []).slice(0, 3).map((s, i) => (
            <span key={i} className={`wiha-persona-pill__chip wiha-persona-pill__chip--${s.tone || 'amber'}`}>
              {s.label}
            </span>
          ))}
        </div>
        <select
          className="wiha-persona-pill__select"
          value={persona.id}
          onChange={(e) => onChange(e.target.value)}
          title="Switch visitor"
        >
          {window.PERSONAS.map(p => (
            <option key={p.id} value={p.id}>{p.userId} · {p.gender}</option>
          ))}
        </select>
      </div>
    </>
  );
}

// =========================================================================
// Why-this-product reason builder
// =========================================================================
function reasonFor(product, persona, favWeights) {
  if (favWeights) {
    const top = product.cats
      .map(c => ({ c, v: favWeights[c] || 0 }))
      .filter(x => x.v >= 0.5)
      .sort((a, b) => b.v - a.v)[0];
    if (top) return { text: `Matches your ♥ ${prettyCat(top.c)}`, kind: 'fav' };
  }
  const w = persona.weights;
  const top = product.cats
    .map(c => ({ c, v: w[c] || 0 }))
    .filter(x => x.v > 0.5)
    .sort((a, b) => b.v - a.v)[0];
  if (top) return { text: `Matches ${prettyCat(top.c)}`, kind: 'fav' };

  const neg = product.cats
    .map(c => ({ c, v: w[c] || 0 }))
    .filter(x => x.v < -0.4)
    .sort((a, b) => a.v - b.v)[0];
  if (neg) return { text: 'Off-persona', kind: 'sim' };
  return null;
}

function prettyCat(c) {
  const m = {
    jacket: 'ski shells & jackets',
    ski: 'ski & mountain',
    sweater: 'merino sweaters',
    zip: '1/4 & full zips',
    hoodie: 'hoodies',
    warm: 'warm layers',
    heavyweight: 'heavyweight merino',
    midweight: 'midweight layers',
    lightweight: 'lightweight merino',
    layer: 'midlayers',
    vest: 'vests',
    'base-layer': 'base layers',
    tee: 'merino tees',
    'long-sleeve': 'long sleeve',
    'short-sleeve': 'short sleeve',
    crew: 'crews',
    henley: 'henleys',
    polo: 'polos',
    tank: 'tanks & camis',
    cami: 'camis',
    top: 'tops',
    bottom: 'bottoms',
    short: 'shorts',
    jogger: 'joggers',
    tight: 'tights',
    pant: 'pants',
    underwear: 'merino underwear',
    sock: 'merino socks',
    beanie: 'beanies',
    glove: 'gloves',
    accessory: 'accessories',
    run: 'run & training',
    hike: 'hike & trail',
    everyday: 'everyday staples',
    travel: 'travel merino',
    merino: 'merino wool',
    'under-50': 'under $50',
    '50-100': '$50–100',
    '100-150': '$100–150',
    '150-250': '$150–250',
    '250-plus': '$250+',
    sale: 'on sale',
    new: 'new arrivals',
    'best-seller': 'best sellers',
  };
  return m[c] || c;
}

Object.assign(window, { SideBySidePLP });
