// ============================================================
// HausMatch App · Screen 1 — Style Quiz
// 60-second visual quiz. Pick A or B across N pairs.
// Ends with an aesthetic fingerprint screen: named primary + secondary style.
// ============================================================

// Named-style profiles shown on the fingerprint result screen.
// Each style gets a short poetic line and a "shape of it" attribute line.
const STYLE_PROFILES = {
  "Desert Modern":        { poetic: "You're drawn to long horizons and the quiet of indoor-outdoor living.", attribute: "Low-slung massing, warm materials, unbroken sightlines." },
  "Coastal Mediterranean":{ poetic: "You want a home that feels like somewhere people have lived for generations.", attribute: "Sun-bleached stucco, terracotta, interior courtyards." },
  "Organic Minimal":      { poetic: "Nothing shouts. Every material earns its place.", attribute: "Warm woods, bone palette, restrained geometry." },
  "Warm Traditional":     { poetic: "You value rooms that have been loved into their shape.", attribute: "Rich woods, layered fabrics, quiet formality." },
  "Soft Brutalist":       { poetic: "Structure and softness, in deliberate tension.", attribute: "Exposed concrete softened with natural warmth." },
  "Tuscan":               { poetic: "Old-world solidity. Rooms with memory.", attribute: "Rough plaster, reclaimed timber, sun-warmed stone." },
  "Modern Hacienda":      { poetic: "Hot climate, cool interiors. A home that knows its place.", attribute: "Terracotta tile, wrought iron, shaded courtyards." },
  "Cape Cod":             { poetic: "Home as landscape — quiet, salted, enduring.", attribute: "White shingles, crisp symmetry, windows to the weather." },
  "Japandi":              { poetic: "The quiet end of minimalism. Everything in its place.", attribute: "Negative space, paper light, honeyed oak." },
  "Classic Revival":      { poetic: "You like rooms that reward a second look.", attribute: "Symmetry, moulding, proportion as decoration." },
  "Warm Minimal":         { poetic: "Less, done well.", attribute: "Pared back, but never cold. Wood, linen, diffused light." },
  "Industrial Loft":      { poetic: "You want the bones to show.", attribute: "Steel, brick, leather, honest seams." },
};

// Tallies picks → returns { primary, secondary } style names.
function computeFingerprint(picks) {
  const counts = {};
  picks.forEach((p, i) => {
    if (p === null || p === undefined) return;
    const pair = window.QUIZ_PAIRS[i];
    if (!pair) return;
    const style = pair[p].style;
    counts[style] = (counts[style] || 0) + 1;
  });
  const sorted = Object.entries(counts).sort((a, b) => b[1] - a[1]);
  return {
    primary: sorted[0] ? sorted[0][0] : null,
    secondary: sorted[1] && sorted[1][0] !== (sorted[0] && sorted[0][0]) ? sorted[1][0] : null,
  };
}

function ScreenQuiz({ onContinue, onFindMatches }) {
  const total = window.QUIZ_PAIRS.length;
  const [idx, setIdx] = React.useState(0);
  const [picks, setPicks] = React.useState(() => Array(total).fill(null));
  const [done, setDone] = React.useState(false);
  const pair = window.QUIZ_PAIRS[idx] || window.QUIZ_PAIRS[0];

  const pick = (i) => {
    const next = [...picks];
    next[idx] = i;
    setPicks(next);
    if (idx < total - 1) {
      setTimeout(() => setIdx(idx + 1), 280);
    } else {
      // Last pair answered. Brief pause so the selection registers visually,
      // then show the fingerprint result.
      setTimeout(() => setDone(true), 520);
    }
  };

  const retake = () => {
    setPicks(Array(total).fill(null));
    setIdx(0);
    setDone(false);
  };

  if (done) {
    const fp = computeFingerprint(picks);
    const primaryProfile = STYLE_PROFILES[fp.primary] || {};
    const secondaryProfile = STYLE_PROFILES[fp.secondary] || {};
    return (
      <div className="screen quiz-screen">
        <AppBar current="quiz" />
        <div className="quiz-main" style={{ maxWidth: 720, margin: "0 auto", padding: "56px 24px 80px", textAlign: "center" }}>
          <div className="quiz-head">
            <Eyebrow>Your aesthetic fingerprint</Eyebrow>
            <h1 className="quiz-title" style={{ marginTop: 18 }}>
              You're <span className="hm-italic-accent">{fp.primary || "undefined"}</span>
              {fp.secondary ? (<><br /><span style={{ fontSize: "0.7em", color: "var(--fg-2)" }}>with <span className="hm-italic-accent">{fp.secondary}</span> restraint</span></>) : null}
              <span style={{ color: "var(--fg-2)" }}>.</span>
            </h1>
            {primaryProfile.poetic && <p className="quiz-sub" style={{ maxWidth: 520, margin: "18px auto 0" }}>{primaryProfile.poetic}</p>}
          </div>

          {primaryProfile.attribute && (
            <div style={{ marginTop: 44, padding: "28px 24px", borderTop: "1px solid var(--pearl-200)", borderBottom: "1px solid var(--pearl-200)" }}>
              <div className="hm-mono" style={{ fontSize: 11, letterSpacing: "0.18em", color: "var(--fg-3)", marginBottom: 10 }}>THE SHAPE OF IT</div>
              <p style={{ fontFamily: "var(--font-display)", fontSize: 20, lineHeight: 1.4, color: "var(--fg-1)", margin: 0 }}>{primaryProfile.attribute}</p>
              {secondaryProfile.attribute && (
                <p style={{ fontFamily: "var(--font-display)", fontSize: 16, lineHeight: 1.4, color: "var(--fg-2)", margin: "14px 0 0", fontStyle: "italic" }}>
                  With touches of {fp.secondary.toLowerCase()}: {secondaryProfile.attribute.toLowerCase()}
                </p>
              )}
            </div>
          )}

          <div className="quiz-actions" style={{ justifyContent: "center", gap: 16, marginTop: 40 }}>
            <button className="quiz-skip" onClick={retake}>
              <Icon name="arrowBack" size={14} />
              Retake
            </button>
            <Button onClick={onFindMatches || onContinue}>
              Find matches <Icon name="arrow" size={14} />
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="screen quiz-screen">
      <AppBar current="quiz" />
      <div className="quiz-main">
        <div className="quiz-head">
          <Eyebrow>The style quiz · 60 seconds</Eyebrow>
          <h1 className="quiz-title">
            Which one <span className="hm-italic-accent">speaks</span> to you?
          </h1>
          <p className="quiz-sub">
            No right answer. Pick by feeling. We'll name your aesthetic.
          </p>
        </div>

        <div className="quiz-pair">
          {pair.map((opt, i) => (
            <button
              key={i}
              className={`quiz-card ${picks[idx] === i ? "is-picked" : ""}`}
              onClick={() => pick(i)}
            >
              <div className="quiz-card-photo">
                <img src={opt.src} alt={opt.style} />
                <span className="quiz-card-letter">{i === 0 ? "A" : "B"}</span>
              </div>
            </button>
          ))}
        </div>

        <div className="quiz-footer">
          <div className="quiz-progress">
            <span className="hm-mono" style={{ fontSize: 11, letterSpacing: "0.14em" }}>
              {String(idx + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
            </span>
            <div className="quiz-progress-bar">
              {Array.from({ length: total }).map((_, i) => (
                <span
                  key={i}
                  className={`quiz-progress-dot ${i <= idx ? "is-past" : ""} ${i === idx ? "is-current" : ""}`}
                />
              ))}
            </div>
          </div>
          <div className="quiz-actions">
            <button
              className="quiz-skip"
              onClick={() => idx > 0 && setIdx(idx - 1)}
              disabled={idx === 0}
            >
              <Icon name="arrowBack" size={14} />
              Back
            </button>
            <button
              className="quiz-skip"
              onClick={onContinue}
            >
              Skip to upload
              <Icon name="arrow" size={14} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenQuiz });
