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

const { useState, useRef, useEffect } = React;
const { fmtPrice, fmtNum, SLOT_LABELS, PRIMARY_SLOTS, SECONDARY_SLOTS } = window.BikeFmt;
const Icon = window.BikeIcon;
const { TopNav, ProfileForm, ComponentCard, SpecCell, ScorePanel, Warnings, BrandTicker } = window.BikeUI;
const { getFramePhoto } = 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>
  );
}

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