// FRD Step 4 — AI reference simulation. For the selected style, renders the
// three intensity variants. Each shows a free warp preview immediately; the
// paid photoreal heal runs only on explicit click (mirrors Step 5). Heals are
// tagged with {style, variant, profile, scale} for A/B attribution.

const VARIANT_META = [
  { key: "realistic", label: "Realistic", blurb: "Conservative, identity-first." },
  { key: "enhanced", label: "Enhanced", blurb: "The style's default targets." },
  { key: "aspirational", label: "Aspirational", blurb: "Pushed toward the ideal." },
];

const VariantColumn = ({ ctx, style, variantKey, profile }) => {
  const { state, set, runHealFor } = ctx;
  const v = style.variants[variantKey];
  const meta = VARIANT_META.find((m) => m.key === variantKey);
  const [previewUrl, setPreviewUrl] = React.useState(null);
  const healed = state.results.find(
    (r) => r.meta && r.meta.style === style.name && r.meta.variant === variantKey
  );

  React.useEffect(() => {
    let alive = true;
    api.warp(state.session.session_id, v.warp)
      .then((r) => { if (alive) setPreviewUrl(r.image_url); })
      .catch(() => {});
    return () => { alive = false; };
  }, [style.key, variantKey]);

  const img = healed ? healed.url : previewUrl;
  const harmonyVal = v.harmony && v.harmony.value != null ? `${v.harmony.value}` : "—";

  return (
    <div className="variant-col">
      <div className="vc-head">
        <span className="vc-label">{meta.label}</span>
        <span className="vc-scale mono-tiny">{v.scale}×</span>
      </div>
      <div className="vc-img">
        {img
          ? <img src={img} alt={meta.label} />
          : <div className="fc-preview-ph mono-tiny">warp preview…</div>}
        {healed && <span className="vc-photoreal mono-tiny">photoreal</span>}
      </div>
      <div className="vc-blurb mono-tiny">{meta.blurb}</div>
      <div className="fc-scores">
        <ScoreChip label="Harmony" value={harmonyVal} />
        <ScoreChip label="Feasibility" value={`${v.feasibility}`} />
        <ScoreChip label="Realism" value={`${v.realism_pct}% EST`} />
      </div>
      <button className="btn btn-primary" disabled={state.healing || !!healed}
        onClick={() => runHealFor(v.warp, { style: style.name, variant: variantKey, profile, scale: v.scale })}>
        {healed ? "Generated ✓" : state.healing ? "Generating…" : "Generate photoreal · ~30s · 1 credit"}
      </button>
      <button className="btn"
        onClick={() => set({ warp: v.warp, preset: "Custom", selectedVariant: variantKey, step: "adjust" })}>
        Refine in Adjust →
      </button>
    </div>
  );
};

const ReferenceStep = ({ ctx }) => {
  const { state, set } = ctx;
  const rec = state.recommendation;
  if (!rec) {
    return (
      <div className="placeholder-step"><div className="ph-inner">
        <h2>No recommendation yet</h2>
        <p>Visit step 3 to generate style recommendations first.</p>
      </div></div>
    );
  }

  const selectedKey = state.selectedStyle || rec.styles[0].key;
  const style = rec.styles.find((s) => s.key === selectedKey) || rec.styles[0];

  return (
    <div className="reference-step">
      <div className="recommend-head">
        <div className="section-label"><span>Reference simulation · {style.name}</span></div>
        <span className="profile-tag mono-tiny">intensity · {rec.profile}</span>
      </div>
      <div className="ref-style-picker">
        {rec.styles.map((s) => (
          <button key={s.key} className={`chip ${s.key === selectedKey ? "active" : ""}`}
            onClick={() => set({ selectedStyle: s.key })}>{s.name}</button>
        ))}
      </div>
      {style.approximation && <div className="fc-approx mono-tiny">≈ {style.approximation}</div>}
      <div className="variant-grid">
        {VARIANT_META.map((m) => (
          <VariantColumn key={m.key} ctx={ctx} style={style} variantKey={m.key} profile={rec.profile} />
        ))}
      </div>
    </div>
  );
};

Object.assign(window, { VARIANT_META, VariantColumn, ReferenceStep });
