// FRD Step 3 — rule-based regional nose-style recommendation. Renders the
// /api/recommend payload as ranked flashcards, each with a free warp-preview
// thumbnail (the enhanced variant) and score chips.

const ScoreChip = ({ label, value, tone }) => (
  <div className={`score-chip ${tone || ""}`}>
    <span className="sc-label">{label}</span>
    <span className="sc-value">{value}</span>
  </div>
);

const _compatTone = (c) => (c >= 70 ? "good" : c >= 50 ? "amber" : "red");

const _harmonyText = (h) => {
  if (!h || h.value == null) return "—";
  if (h.delta == null) return `${h.value}`;
  const sign = h.delta >= 0 ? "+" : "";
  return `${h.value} (${sign}${h.delta})`;
};

const StyleFlashcard = ({ ctx, style, rank }) => {
  const { state, set } = ctx;
  const [previewUrl, setPreviewUrl] = React.useState(null);
  const enhanced = style.variants.enhanced;

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

  return (
    <div className={`flashcard ${style.most_natural_match ? "natural" : ""}`}>
      {style.most_natural_match && <div className="natural-badge">Most Natural Match</div>}
      <div className="fc-rank mono-tiny">#{rank}</div>
      <div className="fc-preview">
        {previewUrl
          ? <img src={previewUrl} alt={style.name} />
          : <div className="fc-preview-ph mono-tiny">warp preview…</div>}
      </div>
      <h3 className="fc-name">{style.name}</h3>
      <ul className="fc-chars">
        {style.characteristics.map((c, i) => <li key={i}>{c}</li>)}
      </ul>
      <div className="fc-metrics">
        <div className="fc-metrics-label mono-tiny">Default targets (aspirational)</div>
        <div className="fc-metric-pills">
          {style.default_metrics.map((m, i) => <span key={i} className="fc-metric-pill">{m}</span>)}
        </div>
      </div>
      {style.approximation && <div className="fc-approx mono-tiny">≈ {style.approximation}</div>}
      <div className="fc-scores">
        <ScoreChip label="Compatibility" value={`${style.compatibility}`} tone={_compatTone(style.compatibility)} />
        <ScoreChip label="Harmony" value={_harmonyText(enhanced.harmony)} />
        <ScoreChip label="Feasibility" value={`${enhanced.feasibility}`} />
        <ScoreChip label="Realism" value={`${enhanced.realism_pct}% EST`} />
      </div>
      <div className="fc-actions">
        <button className="btn btn-primary"
          onClick={() => set({ selectedStyle: style.key, selectedVariant: "enhanced", step: "reference" })}>
          See reference variants →
        </button>
        <button className="btn"
          onClick={() => set({ warp: enhanced.warp, preset: "Custom", step: "adjust" })}>
          Use in Adjust
        </button>
      </div>
    </div>
  );
};

const RecommendStep = ({ ctx }) => {
  const { state, set } = ctx;
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (!state.session || !state.region || !state.gender) return;
    if (state.recommendation) return;
    setLoading(true);
    api.recommend(state.session.session_id, state.region, state.gender)
      .then((rec) => { set({ recommendation: rec, intensityProfile: rec.profile }); setError(null); })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, [state.session && state.session.session_id, state.region, state.gender, state.recommendation]);

  if (!state.session) {
    return (
      <div className="placeholder-step"><div className="ph-inner">
        <h2>Add a portrait first</h2>
        <p>Go to step 1 to pick a region, biological gender and photo.</p>
      </div></div>
    );
  }
  if (!state.region || !state.gender) {
    return (
      <div className="placeholder-step"><div className="ph-inner">
        <h2>Region &amp; gender needed</h2>
        <p>Step 1 needs a region and biological gender before styles can be recommended.</p>
      </div></div>
    );
  }

  const rec = state.recommendation;
  return (
    <div className="recommend-step">
      <div className="recommend-head">
        <div className="section-label"><span>Recommended styles · {state.region} · {state.gender}</span></div>
        {rec && <span className="profile-tag mono-tiny">intensity · {rec.profile}</span>}
      </div>
      {loading && <div className="mono-tiny" style={{ padding: "12px 0" }}>Scoring styles against your analysis…</div>}
      {error && <div className="mono-tiny" style={{ color: "var(--warn)" }}>{error}</div>}
      {rec && (
        <div className="flashcard-grid">
          {rec.styles.map((s, i) => <StyleFlashcard key={s.key} ctx={ctx} style={s} rank={i + 1} />)}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { ScoreChip, StyleFlashcard, RecommendStep });
