// Step 1 — Best Sellers PLP
// Replaces the old homepage carousels. Single-rail product grid with a deep
// red campaign banner, "BEST SELLERS" hero, filter chip row, and Shopping
// Assistant card embedded mid-grid.
//
// Malachyte mode: ranks the same Best Sellers pool by persona + heart signal.
// Alpha mode: alphabetical / static order with red banner overlay.

function StepHome({ state, setState, setMode, mode }) {
  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 = (productId) => {
    setState(s => {
      const favs = s.favorites || [];
      const next = favs.includes(productId) ? favs.filter(x => x !== productId) : [...favs, productId];
      return { ...s, favorites: next };
    });
  };

  const favWeights = window.buildFavWeights ? window.buildFavWeights(favorites) : null;

  // Best Sellers pool — everything in the catalog except pan protectors.
  const bsPool = window.PRODUCTS.filter(p => !p.cats.includes('pan-protector'));

  const ranked = mode === 'malachyte'
    ? window.rankProducts(bsPool, persona, favWeights)
    : window.alphaProducts(bsPool);

  const handleImgErr = (e) => { e.target.src = window.PRODUCT_FALLBACK; };

  // Split for shopping-assistant injection mid-grid
  const head = ranked.slice(0, 6);
  const tail = ranked.slice(6, 18);

  return (
    <div className="bs-root">
      {/* Campaign banner removed per request */}

      {/* Hero removed per request */}

      {mode === 'malachyte' && (
        <PersonaPanel
          persona={persona}
          onPersonaChange={switchPersona}
          favoriteCount={favorites.length}
          state={state}
          setState={setState}
        />
      )}

      <div className="bs-crumb">
        <span>Home</span> / <span className="active">Best Sellers</span>
      </div>

      {mode === 'alpha' && (
        <div className="static-banner static-banner--bs">
          <div className="static-banner__tag">GREENPAN TODAY</div>
          <div className="static-banner__body">
            <b>Every visitor sees the exact same Best Sellers grid.</b> Whether you're a
            Tucci superfan, a first-apartment cook, or a PFAS-conscious replacer — the
            ranking, the hero positions, and the sale tags are identical. No signals,
            no personalization.
          </div>
        </div>
      )}

      {/* Filter row */}
      <div className="bs-filters">
        {['Category', 'Features', 'Material', 'Range', 'Set Size', 'Diameter', 'Capacity', 'Price'].map(f => (
          <button key={f} className="bs-filter" type="button">
            {f.toUpperCase()} <span className="bs-filter__caret">▾</span>
          </button>
        ))}
        <button className="bs-filter bs-filter--sort" type="button">
          SORT BY <span className="bs-filter__caret">▾</span>
        </button>
      </div>

      {/* Optional: malachyte mode reranking banner */}
      {mode === 'malachyte' && (
        <div className="bs-rerank-strip">
          <span className="bs-rerank-strip__tag">MALACHYTE</span>
          <span>
            Ranked for <b>{persona.sessionLabel || persona.name}</b>{persona.starred ? ' ★' : ''}
            {favorites.length > 0 && <> · {favorites.length} ♥ folded in</>}
          </span>
        </div>
      )}

      {/* Grid */}
      <div className="bs-grid">
        {head.map((p, i) => (
          <BSCard key={p.id} product={p} index={i} mode={mode} persona={persona} favWeights={favWeights} favorites={favorites} onFav={toggleFav} onImgErr={handleImgErr} />
        ))}
      </div>

      {/* Shopping Assistant removed per request */}
      <div className="bs-grid">
        {tail.map((p, i) => (
          <BSCard key={p.id} product={p} index={i + 6} mode={mode} persona={persona} favWeights={favWeights} favorites={favorites} onFav={toggleFav} onImgErr={handleImgErr} />
        ))}
      </div>

      <div style={{ height: 60 }} />
    </div>
  );
}

// ============================================================
// Product card — GreenPan PLP style
// ============================================================
function BSCard({ product, index, mode, persona, favWeights, favorites, onFav, onImgErr }) {
  const isFav = favorites && favorites.includes(product.id);
  const score = window.relevanceScore(product, persona, favWeights);
  const reason = mode === 'malachyte' ? reasonFor(product, persona, favWeights) : null;
  const isSale = product.originalPrice && product.originalPrice > product.price;

  return (
    <div className="bs-card">
      <div className="bs-card__media">
        <img src={product.img} alt={product.name} onError={onImgErr} />
        {mode === 'malachyte' && index < 6 && <div className="bs-card__rank">#{index + 1}</div>}
        {product.badge && index < 8 && (
          <div className="bs-card__badge" data-badge={product.badge}>{product.badge}</div>
        )}
        {reason && <div className={`bs-card__why ${reason.kind}`}>{reason.text}</div>}
        {mode === 'malachyte' && (
          <button
            className={`bs-card__fav ${isFav ? 'bs-card__fav--on' : ''}`}
            onClick={(e) => { e.preventDefault(); onFav(product.id); }}
            aria-label={isFav ? 'Remove favorite' : 'Add favorite'}
          >
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
              <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 ? '#E55248' : 'none'} stroke={isFav ? '#E55248' : '#2B2B2B'} strokeWidth="1.6" strokeLinejoin="round" />
            </svg>
          </button>
        )}
      </div>

      <div className="bs-card__body">
        <div className="bs-card__name">{product.name}</div>

        {isSale ? (
          <>
            <div className="bs-card__sugg">Suggested Price ${product.originalPrice.toFixed(2)}</div>
            <div className="bs-card__special">Special ${product.price.toFixed(2)}</div>
          </>
        ) : (
          <div className="bs-card__price">${product.price.toFixed(2)}</div>
        )}

        {product.shippingNote && (
          <div className="bs-card__ship">{product.shippingNote}</div>
        )}
        {product.saleNote && (
          <div className="bs-card__notice">{product.saleNote}</div>
        )}

        {mode === 'malachyte' && (
          <div className="bs-card__score"><span className="bs-card__score-dot" />Score · {score.toFixed(2)}</div>
        )}
      </div>
    </div>
  );
}

// ============================================================
// Shopping Assistant (inline within the grid)
// ============================================================
function BSShoppingAssistant() {
  const chips = [
    "Which do customers love most?",
    "What's a hosting must-have?",
    "What options are beginner-friendly?",
    "What's best for everyday cooking?",
    "How do these differ?",
  ];
  return (
    <div className="bs-assist">
      <div className="bs-assist__head">
        <span className="bs-assist__avatar">
          <img src="assets/greenpan-logo.jpeg" alt="" />
        </span>
        <span className="bs-assist__name">Shopping Assistant</span>
      </div>
      <div className="bs-assist__prompt">
        Need help finding <span className="bs-assist__prompt-q">the right small appliances for hosting?</span>
      </div>
      <div className="bs-assist__chips">
        {chips.map(c => (
          <button key={c} type="button" className="bs-assist__chip">
            <span className="bs-assist__chip-spark">✦</span> {c}
          </button>
        ))}
      </div>
      <div className="bs-assist__input">
        <input type="text" placeholder="What can I help you find?" />
        <button type="button" className="bs-assist__send" aria-label="Send">↑</button>
      </div>
    </div>
  );
}

// ============================================================
// Persona Panel + Why helper (shared with original code)
// ============================================================
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.4)
    .sort((a, b) => b.v - a.v)[0];
  if (!top) {
    const neg = product.cats.find(c => (w[c] || 0) < -0.3);
    if (neg) return { text: 'Off-session', kind: 'sim' };
    return null;
  }
  return { text: `Matches ${prettyCat(top.c)}`, kind: 'fav' };
}

function prettyCat(c) {
  const labels = {
    "stanley-tucci": "Tucci collection", tucci: "Tucci line",
    "valencia-pro": "Valencia Pro", "reserve-pro": "Reserve Pro",
    spectra: "Spectra", premiere: "Premiere", elite: "Elite",
    frost: "Frost", "bobby-flay": "Bobby Flay", gp5: "GP5",
    titanium: "Titanium", platinum: "Platinum", premium: "premium tier",
    mid: "mid tier", value: "value tier", ceramic: "ceramic nonstick",
    stainless: "stainless steel", "carbon-steel": "carbon steel",
    hybrid: "hybrid", "cookware-set": "cookware sets",
    frypan: "frypans", "frypan-set": "frypan sets",
    "knife-block": "knife blocks", "steak-knife": "steak knives",
    "utensil-set": "utensil sets", "bakeware-set": "bakeware",
    "ovenware-set": "ovenware", "ice-cream-maker": "Frost",
    "pizza-oven": "Tucci pizza oven", "air-fryer": "air fryers",
    "slow-cooker": "slow cookers", "rice-cooker": "rice cooker",
    blender: "blenders", blue: "blue tones", "marino-blue": "Marino Blue",
    twilight: "Twilight", sage: "sage tones", cream: "cream tones",
    taupe: "taupe", neutral: "neutrals", gray: "grays",
    wellness: "PFAS-free", "best-seller": "best-sellers", new: "new arrivals",
    trending: "trending", sale: "on sale", cookbook: "Tucci cookbook",
    "gold-handles": "gold-tone handles",
  };
  return labels[c] || c;
}

function PersonaPanel({ persona, onPersonaChange, favoriteCount, state, setState }) {
  const overrides = (state.signalOverrides && state.signalOverrides[persona.id]) || null;
  const signals = overrides || persona.signals || [];

  const updateSignal = (idx, newLabel) => {
    setState(s => {
      const map = { ...(s.signalOverrides || {}) };
      const cur = (map[persona.id] || persona.signals.map(x => ({ ...x }))).map(x => ({ ...x }));
      cur[idx] = { ...cur[idx], label: newLabel };
      map[persona.id] = cur;
      return { ...s, signalOverrides: map };
    });
  };

  const addSignal = () => {
    setState(s => {
      const map = { ...(s.signalOverrides || {}) };
      const cur = (map[persona.id] || persona.signals.map(x => ({ ...x }))).map(x => ({ ...x }));
      const tone = cur[0]?.tone || 'violet';
      cur.push({ label: 'New signal', tone });
      map[persona.id] = cur;
      return { ...s, signalOverrides: map };
    });
  };

  const removeSignal = (idx) => {
    setState(s => {
      const map = { ...(s.signalOverrides || {}) };
      const cur = (map[persona.id] || persona.signals.map(x => ({ ...x }))).map(x => ({ ...x }));
      cur.splice(idx, 1);
      map[persona.id] = cur;
      return { ...s, signalOverrides: map };
    });
  };

  const anchorClasses = ['pp-sig--tl', 'pp-sig--tr', 'pp-sig--bl', 'pp-sig--br'];

  return (
    <div className="persona-panel" data-tone={signals[0]?.tone || 'violet'}>
      <div className="pp-left">
        <label className="pp-dropdown-label">Active user session</label>
        <select
          className="pp-dropdown"
          value={persona.id}
          onChange={(e) => onPersonaChange(e.target.value)}
        >
          {window.PERSONAS.map(p => (
            <option key={p.id} value={p.id}>
              {p.sessionLabel || p.name}{p.starred ? '  ★  scripted' : ''}
            </option>
          ))}
        </select>
        <div className="pp-time-inline">
          <span className="pp-time-pill">🕖 Saturday · 11:22 AM</span>
        </div>
      </div>

      <div className="pp-portrait-wrap">
        <div className="pp-portrait">
          <img src={persona.img} alt={persona.name} />
        </div>
        {signals.map((s, i) => (
          <span
            key={i}
            className={`pp-sig ${anchorClasses[i % 4]} pp-sig--${s.tone}`}
            contentEditable
            suppressContentEditableWarning
            spellCheck={false}
            onBlur={(e) => updateSignal(i, e.currentTarget.textContent.trim() || s.label)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') { e.preventDefault(); e.currentTarget.blur(); }
              if (e.key === 'Backspace' && e.currentTarget.textContent === '' && (e.metaKey || e.altKey)) {
                e.preventDefault();
                removeSignal(i);
              }
            }}
            title="Click to edit · Cmd+Backspace to remove"
          >{s.label}</span>
        ))}
        {/* + add-signal button removed per request */}
      </div>

      <div className="pp-time">
        <div className="pp-time-stack">
          <div className="pp-time-eye">Live session</div>
          <div className="pp-time-note">
            {persona.starred ? '★ Scripted session — drives the demo' : 'Switch sessions to see how ranking changes.'}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StepHome });
