/* global React */
// Bike-Konfigurator — Layout-Varianten

const { useState, useRef, useEffect, useMemo } = React;
const { fmtPrice, fmtNum, SLOT_LABELS, SLOT_TO_POOL, PRIMARY_SLOTS, SECONDARY_SLOTS } = window.BikeFmt;
const Icon = window.BikeIcon;
const { TopNav, ProfileForm, ComponentCard, SpecCell, ScorePanel, Warnings, BrandTicker, detectBrand } = window.BikeUI;
const { getFramePhoto, getComponentPhoto } = window.BikePhotos;
const { GeometryPanel } = window.BikeAdvanced;
const BikeSVG = window.BikeSVG;

// ===== Layout 1: STUDIO (Split-View Default) =====
function StudioLayout(props) {
  const { profile, onProfileChange, result, onSwap, onSave, onReset, onOpenGarage, savedCount, frame, touched } = props;
  return (
    <div className="layout-studio" data-screen-label="Studio Layout">
      {/* LEFT: Cinematic Stage */}
      <div className="stage stage-grid" style={{ position: "relative" }}>
        <StageContent profile={profile} result={result} frame={frame} touched={touched} />
      </div>

      {/* RIGHT: Sidebar */}
      <div className="sidebar">
        <TopNav onOpenGarage={onOpenGarage} savedCount={savedCount} onReset={onReset} user={props.user} onLogout={props.onLogout} plan={props.plan} onUpgrade={props.onUpgrade} />

        <div style={{ padding: "32px 40px 28px" }}>
          <div className="eyebrow eyebrow-accent">Bike-Konfigurator</div>
          <h2 style={{ marginTop: 8, fontSize: 32, lineHeight: 1.1 }} data-comment-anchor="hero-headline">
            Konfiguriere dein Bike.<br /><span style={{ color: "var(--accent)" }}>Algorithmisch.</span>
          </h2>
          <p style={{ marginTop: 14, color: "var(--ink-soft)", maxWidth: 440 }}>
            Profil eingeben, Build entsteht live. Jede Komponente begründet — Sicherheit zuerst, Budget zuletzt.
          </p>
        </div>

        <hr className="divider" />

        <div style={{ padding: "32px 40px" }}>
          <ProfileForm profile={profile} onChange={onProfileChange} />
        </div>

        <hr className="divider" />

        <div style={{ padding: "32px 40px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18 }}>
            <div className="eyebrow">06 — Build</div>
            <div className="eyebrow eyebrow-accent">{result.levels.join(" · ").toUpperCase()}</div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {PRIMARY_SLOTS.map(slot => (
              <ComponentCard key={slot} slot={slot} item={result.build[slot]}
                onClick={() => onSwap(slot)} />
            ))}
          </div>

          {SECONDARY_SLOTS.some(s => result.build[s]) && (
            <details style={{ marginTop: 24 }}>
              <summary style={{ cursor: "pointer", color: "var(--ink-soft)", padding: "12px 0", borderTop: "1px solid var(--hairline)" }}>
                <span className="eyebrow">Kleinteile anzeigen</span>
              </summary>
              <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 8 }}>
                {SECONDARY_SLOTS.map(slot => result.build[slot] && (
                  <ComponentCard key={slot} slot={slot} item={result.build[slot]} onClick={() => onSwap(slot)} />
                ))}
              </div>
            </details>
          )}
        </div>

        <hr className="divider" />

        <div style={{ padding: "32px 40px 24px" }}>
          <Warnings warnings={result.warnings} />
        </div>

        <div style={{ padding: "0 40px 32px" }}>
          <ScorePanel scores={result.scores} />
        </div>

        <Reasoning explanation={result.explanation} />

        <BrandTicker />

        {/* Sticky footer: Preis + Save */}
        <div style={{
          position: "sticky", bottom: 0, marginTop: "auto",
          padding: "20px 40px",
          background: "rgba(15,15,15,0.95)",
          backdropFilter: "blur(14px)",
          borderTop: "1px solid var(--hairline-strong)",
          display: "flex", justifyContent: "space-between", alignItems: "center", gap: 20
        }}>
          <div>
            <div className="eyebrow">Gesamtpreis</div>
            <div style={{
              font: "500 36px/1 var(--font-sans)",
              letterSpacing: "-0.36px",
              fontVariantNumeric: "tabular-nums",
              color: result.total_price > profile.budget ? "var(--accent)" : "var(--ink)",
              marginTop: 4
            }}>
              {fmtPrice(result.total_price)}
            </div>
          </div>
          <button className="btn btn-primary" onClick={onSave}>
            <Icon name="save" size={14} /> Build sichern
          </button>
        </div>
      </div>
    </div>
  );
}

// ===== Stage Content (zentral, beide Layouts nutzen es) =====
function StageContent({ profile, result, frame, touched }) {
  const [showGeo, setShowGeo] = useState(false);
  const visible = {
    fork: touched?.has("fork"),
    shock: touched?.has("shock"),
    wheels: touched?.has("wheels"),
    tires: touched?.has("tires"),
    drivetrain: touched?.has("drivetrain"),
    brakes: touched?.has("brakes"),
    cockpit: touched?.has("cockpit"),
    saddle: touched?.has("saddle"),
    dropper: touched?.has("dropper")
  };
  const totalWeight = ((frame.weight_g || 0)
    + (result.build.fork?.weight_g || 0)
    + (result.build.wheels?.weight_g || 0)
    + (result.build.tires?.weight_g || 0) * 2
    + (result.build.drivetrain?.weight_g || 0)
    + (result.build.brakes?.weight_g || 0)) / 1000;

  // Progress
  const totalParts = 9;
  const builtParts = Object.values(visible).filter(Boolean).length;
  const pct = Math.round((builtParts / totalParts) * 100);

  return (
    <>
      {/* Subtle dark gradient bg */}
      <div className="stage-bg-solid" />

      {/* Geo toggle */}
      <button className="geo-toggle" onClick={() => setShowGeo(!showGeo)}>
        <span style={{ width: 6, height: 6, background: showGeo ? "var(--accent)" : "var(--ink-soft)", display: "inline-block" }} />
        Geometrie
      </button>

      {showGeo && (
        <GeometryPanel frame={frame} build={result.build} onClose={() => setShowGeo(false)} />
      )}

      <div style={{ position: "relative", zIndex: 2, padding: 48, width: "100%", height: "100%", display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
        {/* Top — frame name */}
        <div style={{ maxWidth: 720 }}>
          <div className="eyebrow eyebrow-accent">{frame.category.toUpperCase()} — {frame.travel_mm} mm{frame.id?.startsWith("frame_emtb") ? " · E-BIKE" : ""}</div>
          <div style={{ font: "500 64px/1.04 var(--font-sans)", letterSpacing: "-1.28px", marginTop: 14 }} data-comment-anchor="frame-headline">
            {frame.name}
          </div>
        </div>

        {/* Center — progressive bike */}
        <div style={{ flex: 1, display: "grid", placeItems: "center", margin: "16px 0", minHeight: 280, position: "relative" }}>
          <div style={{ width: "100%", maxWidth: 900, aspectRatio: "5 / 3" }}>
            <BikeSVG frame={frame} build={result.build} visible={visible} />
          </div>
        </div>

        {/* Bottom — spec strip */}
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(4, 1fr) auto", gap: 32,
          paddingTop: 24, alignItems: "end",
          borderTop: "1px solid rgba(255,255,255,0.18)"
        }}>
          <SpecCell label="Reach" value={frame.reach} unit="mm" />
          <SpecCell label="Stack" value={frame.stack} unit="mm" />
          <SpecCell label="Federweg" value={frame.travel_mm} unit="mm" accent />
          <SpecCell label="Gewicht" value={fmtNum(totalWeight)} unit="kg" />
          <div style={{ minWidth: 160 }}>
            <div className="spec-label" style={{ marginBottom: 8 }}>Build-Fortschritt</div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
              <span style={{ font: "500 28px/1 var(--font-sans)", fontVariantNumeric: "tabular-nums", color: "var(--accent)" }}>{pct}</span>
              <span className="spec-unit">%</span>
            </div>
            <div className="score-bar" style={{ marginTop: 8 }}>
              <div className="score-bar-fill is-accent" style={{ width: `${pct}%` }} />
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// Render BikeSVG correctly — replace the wrapper above
// (Inline render at usage site since window.BikeSVG IS the component)

// ===== Reasoning -----
function Reasoning({ explanation }) {
  if (!explanation) return null;
  const sections = [
    { title: "Warum dieser Build", items: explanation.reasons, color: "var(--ink)" },
    { title: "Stärken", items: explanation.strengths, color: "var(--accent)" },
    { title: "Kompromisse", items: explanation.compromises, color: "var(--ink-soft)" },
  ].filter(s => s.items && s.items.length);
  return (
    <div style={{ padding: "32px 40px", borderTop: "1px solid var(--hairline)" }}>
      {sections.map((s, i) => (
        <div key={i} style={{ marginBottom: 24 }}>
          <div className="eyebrow" style={{ color: s.color, marginBottom: 12 }}>{s.title}</div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
            {s.items.map((it, j) => (
              <li key={j} style={{ color: "var(--ink-soft)", display: "flex", gap: 10, alignItems: "flex-start" }}>
                <span style={{ color: s.color, marginTop: 6 }}>—</span>
                <span style={{ font: "400 14px/1.55 var(--font-sans)" }}>{it}</span>
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}

// ===== Layout 2: EDITORIAL (vertical scroll) =====
function EditorialLayout(props) {
  const { profile, onProfileChange, result, onSwap, onSave, onReset, onOpenGarage, savedCount, frame, touched } = props;
  return (
    <div data-screen-label="Editorial Layout">
      <TopNav onOpenGarage={onOpenGarage} savedCount={savedCount} onReset={onReset} user={props.user} onLogout={props.onLogout} plan={props.plan} onUpgrade={props.onUpgrade} />

      {/* HERO band */}
      <div className="stage stage-grid" style={{ position: "relative", minHeight: "92vh", paddingTop: 48 }}>
        <StageContent profile={profile} result={result} frame={frame} touched={touched} />
      </div>

      {/* Profile band */}
      <section style={{ background: "var(--canvas-elevated)", padding: "96px 64px", borderTop: "1px solid var(--hairline)" }}>
        <div style={{ maxWidth: 1280, margin: "0 auto" }}>
          <div className="eyebrow eyebrow-accent">Profil</div>
          <h2 style={{ marginTop: 14, fontSize: 56, letterSpacing: "-1.12px" }}>Wer fährt das Bike.</h2>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 64, marginTop: 48 }}>
            <ProfileForm profile={profile} onChange={onProfileChange} />
            <div>
              <ScorePanel scores={result.scores} />
              <div style={{ marginTop: 32 }}>
                <Warnings warnings={result.warnings} />
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Build band */}
      <section style={{ padding: "96px 64px", borderTop: "1px solid var(--hairline)" }}>
        <div style={{ maxWidth: 1280, margin: "0 auto" }}>
          <div className="eyebrow eyebrow-accent">Build</div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 14 }}>
            <h2 style={{ fontSize: 56, letterSpacing: "-1.12px" }}>Komponenten.</h2>
            <div className="eyebrow">{result.levels.join(" · ").toUpperCase()} TIER</div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 48 }}>
            {PRIMARY_SLOTS.map(slot => (
              <ComponentCard key={slot} slot={slot} item={result.build[slot]} onClick={() => onSwap(slot)} />
            ))}
          </div>
        </div>
      </section>

      {/* Reasoning band */}
      <section style={{ padding: "96px 64px", background: "var(--canvas-elevated)", borderTop: "1px solid var(--hairline)" }}>
        <div style={{ maxWidth: 1280, margin: "0 auto" }}>
          <div className="eyebrow eyebrow-accent">Reasoning</div>
          <h2 style={{ fontSize: 56, letterSpacing: "-1.12px", marginTop: 14, marginBottom: 32 }}>Warum dieser Build.</h2>
          <Reasoning explanation={result.explanation} />
        </div>
      </section>

      {/* CTA Band */}
      <section style={{ background: "var(--gradient-rosso)", padding: "64px", textAlign: "center" }}>
        <div className="eyebrow" style={{ color: "rgba(255,255,255,0.8)" }}>Gesamtpreis</div>
        <div style={{ font: "500 96px/1 var(--font-sans)", letterSpacing: "-1.92px", marginTop: 14, color: "#fff" }}>
          {fmtPrice(result.total_price)}
        </div>
        <button className="btn btn-outline" style={{ marginTop: 32, color: "#fff", boxShadow: "inset 0 0 0 1px #fff" }} onClick={onSave}>
          <Icon name="save" size={14} /> Build sichern
        </button>
      </section>
    </div>
  );
}

// ===== Layout 3: GARAGE (Dashboard) =====
function GarageLayout(props) {
  const { profile, onProfileChange, result, onSwap, onSave, onReset, onOpenGarage, savedCount, frame, touched } = props;
  return (
    <div style={{ minHeight: "100vh", background: "var(--canvas-deep)" }} data-screen-label="Garage Dashboard">
      <TopNav onOpenGarage={onOpenGarage} savedCount={savedCount} onReset={onReset} user={props.user} onLogout={props.onLogout} plan={props.plan} onUpgrade={props.onUpgrade} />

      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr 360px", gap: 1, background: "var(--hairline)", minHeight: "calc(100vh - 64px)" }}>
        {/* LEFT: Profile */}
        <div style={{ background: "var(--canvas-elevated)", padding: 32, overflow: "auto" }}>
          <div className="eyebrow eyebrow-accent">Profil</div>
          <h3 style={{ marginTop: 8, marginBottom: 24, fontSize: 22 }}>Fahrer</h3>
          <ProfileForm profile={profile} onChange={onProfileChange} />
        </div>

        {/* CENTER: Stage + Build */}
        <div style={{ background: "var(--canvas)", display: "flex", flexDirection: "column" }}>
          <div className="stage stage-grid" style={{ position: "relative", minHeight: 460, flex: "0 0 auto" }}>
            <StageContent profile={profile} result={result} frame={frame} touched={touched} />
          </div>
          <div style={{ padding: 32, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, borderTop: "1px solid var(--hairline)" }}>
            {PRIMARY_SLOTS.map(slot => (
              <ComponentCard key={slot} slot={slot} item={result.build[slot]} onClick={() => onSwap(slot)} />
            ))}
          </div>
        </div>

        {/* RIGHT: Scores + Reasoning + Price */}
        <div style={{ background: "var(--canvas-elevated)", display: "flex", flexDirection: "column", overflow: "auto" }}>
          <div style={{ padding: 32, borderBottom: "1px solid var(--hairline)" }}>
            <div className="eyebrow eyebrow-accent">Scoring</div>
            <div style={{ marginTop: 24 }}>
              <ScorePanel scores={result.scores} />
            </div>
          </div>
          <div style={{ padding: 32, borderBottom: "1px solid var(--hairline)" }}>
            <Warnings warnings={result.warnings} />
          </div>
          <div style={{ flex: 1, overflow: "auto" }}>
            <Reasoning explanation={result.explanation} />
          </div>
          <div style={{
            padding: "24px 32px",
            borderTop: "1px solid var(--hairline-strong)",
            background: "rgba(15,15,15,0.95)",
            display: "flex", justifyContent: "space-between", alignItems: "center"
          }}>
            <div>
              <div className="eyebrow">Total</div>
              <div style={{ font: "500 28px/1 var(--font-sans)", letterSpacing: "-0.36px", fontVariantNumeric: "tabular-nums", marginTop: 4, color: result.total_price > profile.budget ? "var(--accent)" : "var(--ink)" }}>
                {fmtPrice(result.total_price)}
              </div>
            </div>
            <button className="btn btn-primary btn-sm" onClick={onSave}>
              <Icon name="save" size={14} /> Sichern
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ===== WIZARD LAYOUT =====

const WIZARD_SLOTS = ['frame', 'fork', 'shock', 'wheels', 'tires', 'drivetrain', 'brakes', 'cockpit', 'dropper'];

function getWizardPool(slot, frame, profile, frames, components) {
  if (slot === 'frame') return frames || [];
  const key = SLOT_TO_POOL[slot];
  if (!key || !components) return [];
  let pool = (components[key] || []).slice();
  if (slot === 'wheels') {
    pool = pool.filter(w => (!w.wheel_sizes || w.wheel_sizes.includes(frame.wheel_size)) && (!w.axle_front || w.axle_front === frame.axle_front));
  } else if (slot === 'fork') {
    pool = pool.filter(f => (!f.wheel_sizes || f.wheel_sizes.includes(frame.wheel_size)) && (!f.axle || f.axle === frame.axle_front));
  } else if (slot === 'tires') {
    pool = pool.filter(t => !t.terrain || t.terrain === profile.terrain);
  } else if (slot === 'dropper') {
    pool = pool.filter(d => !d.seatpost_diameters || d.seatpost_diameters.includes(frame.seatpost_diameter));
  } else if (slot === 'shock') {
    if (frame.is_hardtail) return [];
    if (frame.shock_size_class) pool = pool.filter(s => !s.size_class || s.size_class.includes(frame.shock_size_class));
  }
  return pool.sort((a, b) => (a.price || 0) - (b.price || 0));
}

function getLevelVariants(pool) {
  const ORDER = ['entry', 'mid_low', 'mid', 'mid_high', 'high'];
  const levels = [...new Set(pool.map(p => p.level).filter(Boolean))];
  return levels.length > 1 ? levels.sort((a, b) => ORDER.indexOf(a) - ORDER.indexOf(b)) : null;
}

function getSpecVariants(slot, pool) {
  if (slot === 'fork' || slot === 'shock') {
    const vals = [...new Set(pool.map(p => p.travel_mm).filter(Boolean))].sort((a, b) => a - b);
    return vals.length > 1 ? vals.map(v => ({ label: `${v} mm`, match: p => p.travel_mm === v })) : null;
  }
  if (slot === 'wheels') {
    const vals = [...new Set(pool.flatMap(p => p.wheel_sizes || []))].sort();
    return vals.length > 1 ? vals.map(v => ({ label: `${v}"`, match: p => (p.wheel_sizes || []).includes(v) })) : null;
  }
  if (slot === 'dropper') {
    const vals = [...new Set(pool.flatMap(p => p.seatpost_diameters || []))].sort((a, b) => a - b);
    return vals.length > 1 ? vals.map(v => ({ label: `${v} mm`, match: p => (p.seatpost_diameters || []).includes(v) })) : null;
  }
  return null;
}

function getSpecValue(slot, item) {
  if (!item) return null;
  if (slot === 'fork' || slot === 'shock') return item.travel_mm ? `${item.travel_mm} mm` : null;
  if (slot === 'wheels') return item.wheel_sizes ? item.wheel_sizes.map(s => `${s}"`).join(' / ') : null;
  if (slot === 'dropper') return item.seatpost_diameters ? item.seatpost_diameters.join(' / ') + ' mm' : null;
  return null;
}

// ---- Wizard Product Detail Panel (right side) ----
function WizardProductPanel({ slot, item, pool, preview, onPreview, onAdd, isLastStep }) {
  if (!item && !preview) {
    return (
      <div className="wizard-detail-inner" style={{ color: 'var(--ink-muted)', paddingTop: 48, textAlign: 'center' }}>
        <Icon name={slot} size={40} />
        <div className="eyebrow" style={{ marginTop: 16 }}>Produkt auswählen</div>
      </div>
    );
  }
  const displayItem = preview || item;
  const brand = displayItem.brand || detectBrand(displayItem.name) || (displayItem.category || slot).toUpperCase();
  const levels = getLevelVariants(pool);
  const specVariants = getSpecVariants(slot, pool);
  const specValue = getSpecValue(slot, displayItem);

  const handleLevelClick = (lv) => {
    const match = pool.find(p => p.level === lv);
    if (match) onPreview(match);
  };

  const handleSpecClick = (sv) => {
    const match = pool.find(sv.match);
    if (match) onPreview(match);
  };

  const levelOrder = ['entry', 'mid_low', 'mid', 'mid_high', 'high'];
  const levelLabels = { entry: 'Entry', mid_low: 'Mid-Low', mid: 'Mid', mid_high: 'Mid-High', high: 'High' };

  return (
    <div className="wizard-detail-inner">
      <div className="wizard-detail-brand">{brand}</div>
      <h2 className="wizard-detail-name">{displayItem.name}</h2>
      <div className="wizard-detail-price">{fmtPrice(displayItem.price || 0)}</div>
      <div className="wizard-detail-meta">
        <span>Artikelnummer: {displayItem.id}</span>
        {displayItem.weight_g != null && <span>Gewicht: {displayItem.weight_g} g</span>}
        {displayItem.travel_mm != null && slot !== 'fork' && slot !== 'shock' && <span>Federweg: {displayItem.travel_mm} mm</span>}
      </div>

      {levels && (
        <div className="wizard-variant-group">
          <div className="wizard-variant-label">
            Stufe: <span>{levelLabels[displayItem.level] || displayItem.level || '—'}</span>
          </div>
          <div className="wizard-variant-options">
            {levels.map(lv => (
              <button key={lv}
                className={'wizard-variant-btn' + (displayItem.level === lv ? ' is-active' : '')}
                onClick={() => handleLevelClick(lv)}>
                {levelLabels[lv] || lv}
              </button>
            ))}
          </div>
        </div>
      )}

      {specVariants && (
        <div className="wizard-variant-group">
          <div className="wizard-variant-label">
            Größe: <span>{specValue || '—'}</span>
          </div>
          <div className="wizard-variant-options">
            {specVariants.map((sv, i) => {
              const match = pool.find(sv.match);
              const isActive = match && displayItem.id === match.id;
              return (
                <button key={i}
                  className={'wizard-variant-btn' + (isActive ? ' is-active' : '')}
                  onClick={() => handleSpecClick(sv)}>
                  {sv.label}
                </button>
              );
            })}
          </div>
        </div>
      )}

      <div className="wizard-stock-label" style={{ color: '#22c55e' }}>Auf Lager</div>

      <button className="wizard-add-btn" onClick={onAdd}>
        {isLastStep ? 'Build abschließen →' : 'Zum Erstellen hinzufügen'}
      </button>
    </div>
  );
}

// ---- Wizard Product Grid (bottom) ----
function WizardProductGrid({ slot, pool, activeItem, onSelect }) {
  if (!pool || pool.length === 0) {
    return (
      <div style={{ padding: 32, color: 'var(--ink-muted)', textAlign: 'center' }}>
        <Icon name={slot} size={40} />
        <div className="eyebrow" style={{ marginTop: 14 }}>Keine kompatiblen Produkte</div>
      </div>
    );
  }
  const maxPrice = Math.max(...pool.map(p => p.price || 0));

  return (
    <div className="wizard-product-grid">
      {pool.map(item => {
        const isActive = activeItem && activeItem.id === item.id;
        const brand = item.brand || detectBrand(item.name);
        const savings = maxPrice > 0 ? maxPrice - (item.price || 0) : 0;
        const showSavings = savings > 80 && (item.price || 0) < maxPrice * 0.80;
        const photo = item.photo_url || (slot === 'frame' ? getFramePhoto(item) : getComponentPhoto(slot, item));

        return (
          <div key={item.id}
            className={'wizard-product-card' + (isActive ? ' is-active' : '')}
            onClick={() => onSelect(item)}>
            <div className="wizard-product-card-image"
              style={photo ? {
                backgroundImage: `url(${photo})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                filter: isActive ? 'brightness(0.85)' : 'brightness(0.6) saturate(0.7)'
              } : {}}>
              {!photo && <Icon name={slot} size={52} />}
              {showSavings && (
                <div className="wizard-savings-badge">Spare {fmtPrice(savings)}</div>
              )}
              {brand && (
                <div style={{
                  position: 'absolute', bottom: 8, left: 8,
                  background: 'rgba(0,0,0,0.75)',
                  backdropFilter: 'blur(6px)',
                  padding: '3px 7px',
                  font: '700 8px/1 var(--font-sans)',
                  letterSpacing: '1.2px',
                  textTransform: 'uppercase',
                  color: 'rgba(255,255,255,0.8)'
                }}>{brand}</div>
              )}
            </div>
            <div className="wizard-product-card-body">
              <div className="wizard-product-card-name">{item.name}</div>
              <div className="wizard-product-card-price">{fmtPrice(item.price || 0)}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ---- Wizard Layout ----
function WizardLayout(props) {
  const { profile, result, onSave, onReset, onOpenGarage, frame, frames, components, onPickSlot } = props;

  const [step, setStep] = useState(0);
  const [preview, setPreview] = useState(null);

  const slots = useMemo(
    () => WIZARD_SLOTS.filter(s => !(s === 'shock' && frame.is_hardtail)),
    [frame.is_hardtail]
  );

  const currentSlot = slots[step];

  const pool = useMemo(
    () => getWizardPool(currentSlot, frame, profile, frames, components),
    [currentSlot, frame, profile, frames, components]
  );

  const currentItem = result.build[currentSlot];
  const displayItem = preview || currentItem;

  const totalWeightKg = (
    (frame.weight_g || 0) +
    (result.build.fork?.weight_g || 0) +
    (result.build.wheels?.weight_g || 0) +
    (result.build.tires?.weight_g || 0) * 2 +
    (result.build.drivetrain?.weight_g || 0) +
    (result.build.brakes?.weight_g || 0)
  ) / 1000;
  const totalWeightLbs = totalWeightKg * 2.205;

  const goNext = () => {
    if (step < slots.length - 1) { setStep(step + 1); setPreview(null); }
    else { onSave(); }
  };

  const handleAdd = () => {
    const toApply = preview || currentItem;
    if (toApply && onPickSlot) onPickSlot(currentSlot, toApply);
    goNext();
  };

  const handleBack = () => {
    if (step > 0) { setStep(step - 1); setPreview(null); }
  };

  const handleSkip = () => goNext();

  const handleRestart = () => { onReset(); setStep(0); setPreview(null); };

  const framePhoto = getFramePhoto(frame);
  const isLastStep = step === slots.length - 1;

  return (
    <div className="layout-wizard">
      {/* Upper area: hero + product detail */}
      <div className="wizard-main">
        {/* Left: frame photo + nav */}
        <div className="wizard-hero">
          <div className="wizard-hero-img"
            style={{ backgroundImage: framePhoto ? `url(${framePhoto})` : 'none' }} />
          <div className="wizard-hero-watermark">{frame.category || 'BIKE'}</div>

          {/* Nav bar */}
          <div className="wizard-nav">
            <div className="wizard-nav-buttons">
              <button className="btn btn-outline btn-sm" onClick={handleBack} disabled={step === 0}
                style={step === 0 ? { opacity: 0.35 } : {}}>
                Zurück
              </button>
              <button className="btn btn-outline btn-sm" onClick={() => onOpenGarage?.()}>
                Rezension
              </button>
              <button className="btn btn-outline btn-sm" onClick={handleRestart}>
                Neustart
              </button>
              <button className="btn btn-sm" onClick={handleSkip} disabled={isLastStep}
                style={{
                  background: 'rgba(255,255,255,0.08)',
                  color: isLastStep ? 'var(--ink-muted)' : 'var(--ink-soft)',
                  border: '1px solid var(--hairline-strong)'
                }}>
                Überspringen
              </button>
            </div>
            <div className="wizard-nav-price">
              <div className="wizard-nav-price-total">{fmtPrice(result.total_price)}</div>
              <div className="wizard-nav-price-weight">
                {fmtNum(totalWeightLbs)} Pfund ({fmtNum(totalWeightKg * 100) / 100} kg)
              </div>
            </div>
          </div>
        </div>

        {/* Right: product detail panel */}
        <div className="wizard-detail">
          {/* Step progress pips */}
          <div className="wizard-steps">
            {slots.map((s, i) => (
              <div key={s} className={
                'wizard-step-pip' +
                (i < step ? ' is-done' : i === step ? ' is-current' : '')
              } onClick={() => { setStep(i); setPreview(null); }}
              style={{ cursor: 'pointer' }} />
            ))}
          </div>

          <WizardProductPanel
            slot={currentSlot}
            item={currentItem}
            pool={pool}
            preview={preview}
            onPreview={setPreview}
            onAdd={handleAdd}
            isLastStep={isLastStep}
          />
        </div>
      </div>

      {/* Lower area: product grid */}
      <div className="wizard-grid-section">
        <div className="wizard-grid-header">
          <h3 className="wizard-grid-title">{(SLOT_LABELS[currentSlot] || currentSlot).toUpperCase()} AUSWÄHLEN</h3>
          <div className="wizard-grid-controls">
            <button className="btn btn-ghost btn-tiny" style={{ color: 'var(--ink-soft)', padding: '6px 10px' }}>
              <Icon name="list" size={13} /> Filter anzeigen
            </button>
            <span className="eyebrow" style={{ color: 'var(--ink-muted)' }}>{pool.length} Produkte</span>
          </div>
        </div>

        <WizardProductGrid
          slot={currentSlot}
          pool={pool}
          activeItem={displayItem}
          onSelect={setPreview}
        />
      </div>
    </div>
  );
}

window.BikeLayouts = { StudioLayout, EditorialLayout, GarageLayout, WizardLayout };
