// app/bets.jsx — Place your bets v2 : 12 paris + 1 secret, 3 catégories, 3 types
// (qcm · yesno · slider). Recap final, easter egg Phila #2.

const BETS_KEY        = "ea-app:bets";
const BETS_SUBMIT_KEY = "ea-app:bets:submissions";
const BETS_NAME_KEY   = "ea-app:bets:name";
const PHILA_BET_KEY   = "ea-app:bets:phila";

function BetsPage() {
  const [bets, setBets] = React.useState(() => Store.get(BETS_KEY, {}));
  const [name, setName] = React.useState(() => Store.get(BETS_NAME_KEY, ""));
  const [showRecap, setShowRecap] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(() => {
    const all = Store.get(BETS_SUBMIT_KEY, []);
    const last = Store.get(BETS_NAME_KEY, "");
    return all.some((s) => s.name.toLowerCase() === last.toLowerCase()) && last.length > 0;
  });
  const [philaUnlocked, setPhilaUnlocked] = React.useState(() => Store.get(PHILA_BET_KEY + ":unlocked", false));
  const [philaAnswer, setPhilaAnswer] = React.useState(() => Store.get(PHILA_BET_KEY, null));

  const pickBet = (qid, opt) => {
    const next = { ...bets, [qid]: opt };
    setBets(next);
    Store.set(BETS_KEY, next);
  };

  const total = APP_DATA.bets.length;
  const answered = Object.keys(bets).filter((k) => bets[k] !== undefined && bets[k] !== null && bets[k] !== "").length;
  const progress = Math.round((answered / total) * 100);

  const handleValidate = () => {
    if (name.trim().length < 2) {
      alert("Indiquez votre prénom et nom avant de valider.");
      return;
    }
    setShowRecap(true);
  };

  const handleSubmit = () => {
    Store.set(BETS_NAME_KEY, name.trim());
    const all = Store.get(BETS_SUBMIT_KEY, []);
    const filtered = all.filter((r) => r.name.toLowerCase() !== name.trim().toLowerCase());
    filtered.push({ name: name.trim(), bets, at: new Date().toISOString() });
    Store.set(BETS_SUBMIT_KEY, filtered);
    setSubmitted(true);
    setShowRecap(false);
  };

  const handlePhilaBet = (opt) => {
    setPhilaAnswer(opt);
    setPhilaUnlocked(true);
    Store.set(PHILA_BET_KEY, opt);
    Store.set(PHILA_BET_KEY + ":unlocked", true);
  };

  // ───── ÉCRAN : RECAP avant validation ─────
  if (showRecap) {
    return <BetsRecap bets={bets} name={name} onCancel={() => setShowRecap(false)} onConfirm={handleSubmit} />;
  }

  // ───── ÉCRAN : SOUMIS ─────
  if (submitted) {
    return (
      <BetsSubmitted
        name={name}
        bets={bets}
        philaUnlocked={philaUnlocked}
        philaAnswer={philaAnswer}
        onPhilaBet={handlePhilaBet}
        onModify={() => setSubmitted(false)}
      />
    );
  }

  // ───── ÉCRAN : SAISIE PARIS ─────
  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={0} opacity={0.18}/>
      <Page>
        <AppHeader eyebrow="Place your bets" title="Faites vos jeux" />
        <div style={{ textAlign: "center", fontFamily: A.italic, fontStyle: "italic", fontSize: 16, color: A.inkSoft, marginTop: 6, maxWidth: 480, margin: "8px auto 0", lineHeight: 1.55 }}>
          12 pronostics. 3 catégories. <br/>
          Le plus juste après le 21 août remporte une carte signée du couple.
        </div>

        {/* Progress */}
        <div style={{ marginTop: 28, padding: "16px 18px", background: A.ink, color: A.white }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
            <span style={{ fontFamily: A.mono, fontSize: 10, letterSpacing: 2, color: A.or, textTransform: "uppercase" }}>Vos mises</span>
            <span style={{ fontFamily: A.mono, fontSize: 12, color: A.white, fontWeight: 600 }}>{answered} / {total}</span>
          </div>
          <div style={{ height: 4, background: "rgba(255,255,255,0.15)", overflow: "hidden", borderRadius: 2 }}>
            <div style={{ width: `${progress}%`, height: "100%", background: A.or, transition: "width .3s ease" }}/>
          </div>
        </div>

        {/* Sections par catégorie */}
        {APP_DATA.betCategories.map((cat) => {
          const catBets = APP_DATA.bets.filter((b) => b.category === cat.id);
          return (
            <div key={cat.id} style={{ marginTop: 36 }}>
              <BetsSectionHeader icon={cat.icon} title={cat.title} sub={cat.sub} />
              <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 16 }}>
                {catBets.map((b) => (
                  <BetCard
                    key={b.id}
                    bet={b}
                    index={APP_DATA.bets.indexOf(b)}
                    value={bets[b.id]}
                    onChange={(v) => pickBet(b.id, v)}
                  />
                ))}
              </div>
            </div>
          );
        })}

        {/* Validation */}
        <div style={{ marginTop: 36, padding: "20px 22px", background: A.card, border: `1px solid ${A.ruleSoft}`, boxShadow: A.shadow }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Votre identité</div>
          <input
            type="text" value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Prénom et nom (pour le scoreboard)"
            style={{
              width: "100%", padding: "13px 16px", background: A.paper,
              border: `1.5px solid ${A.ruleSoft}`, fontFamily: A.sans, fontSize: 15, color: A.ink, outline: "none",
              marginBottom: 14,
            }}
          />
          <ButtonA primary full onClick={handleValidate}>
            ♠ Valider mes {answered} mise{answered > 1 ? "s" : ""}
          </ButtonA>
          {answered < total && (
            <div style={{ marginTop: 12, fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute, textAlign: "center" }}>
              Il vous reste {total - answered} mise{total - answered > 1 ? "s" : ""} à faire. Vous pouvez aussi valider partiellement.
            </div>
          )}
        </div>
      </Page>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Section header
// ─────────────────────────────────────────────────────────
function BetsSectionHeader({ icon, title, sub }) {
  return (
    <div style={{ display: "flex", alignItems: "baseline", gap: 12, padding: "0 4px" }}>
      <span style={{ fontFamily: A.display, fontStyle: "italic", fontSize: 32, color: A.rouge, fontWeight: 400, lineHeight: 1 }}>{icon}</span>
      <div style={{ flex: 1 }}>
        <div className="display-bold" style={{ fontSize: 22, color: A.ink, letterSpacing: -0.4 }}>{title}</div>
        <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.inkSoft }}>{sub}</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Carte de pari (dispatch par type)
// ─────────────────────────────────────────────────────────
function BetCard({ bet, index, value, onChange }) {
  return (
    <div style={{
      background: A.white, border: `1px solid ${A.ruleSoft}`, borderRadius: 4,
      padding: "20px 20px 18px", boxShadow: A.shadow,
      position: "relative", overflow: "hidden",
    }}>
      <div style={{ position: "absolute", top: 10, left: 12, color: A.rouge, fontSize: 14, opacity: 0.4 }}>♥</div>
      <div style={{ position: "absolute", bottom: 10, right: 12, color: A.rouge, fontSize: 14, opacity: 0.4, transform: "rotate(180deg)" }}>♥</div>

      <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 14 }}>
        <span style={{ color: A.or, fontFamily: A.display, fontSize: 18 }}>{bet.icon}</span>
        <span style={{ fontFamily: A.mono, fontSize: 10, letterSpacing: 2, color: A.inkMute }}>
          {String(index + 1).padStart(2, "0")}
        </span>
        <span style={{
          fontFamily: A.display, fontStyle: "italic", fontWeight: 400,
          fontSize: 19, color: A.ink, lineHeight: 1.25, letterSpacing: -0.3, flex: 1,
          textWrap: "balance",
        }}>
          {bet.q}
        </span>
      </div>

      {bet.type === "qcm"   && <QcmOptions   bet={bet} value={value} onChange={onChange} />}
      {bet.type === "yesno" && <YesNoOptions bet={bet} value={value} onChange={onChange} />}
      {bet.type === "slider"&& <SliderOption bet={bet} value={value} onChange={onChange} />}
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Type QCM
// ─────────────────────────────────────────────────────────
function QcmOptions({ bet, value, onChange }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      {bet.options.map((opt) => {
        const selected = value === opt;
        return (
          <button key={opt} onClick={() => onChange(opt)} style={{
            textAlign: "left", padding: "11px 14px",
            background: selected ? A.rouge : A.paper,
            color: selected ? A.white : A.ink,
            border: `1px solid ${selected ? A.rouge : A.ruleSoft}`,
            fontFamily: A.sans, fontSize: 13.5, cursor: "pointer",
            transition: "all .12s", fontWeight: selected ? 600 : 400,
            display: "flex", alignItems: "center", gap: 10,
          }}>
            <span style={{
              width: 16, height: 16, borderRadius: "50%",
              border: `1.5px solid ${selected ? A.white : A.inkMute}`,
              background: selected ? A.white : "transparent",
              flexShrink: 0,
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              {selected && <span style={{ width: 6, height: 6, borderRadius: "50%", background: A.rouge }}/>}
            </span>
            {opt}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Type Yes/No
// ─────────────────────────────────────────────────────────
function YesNoOptions({ bet, value, onChange }) {
  const options = [
    { v: "oui", label: "Oui",  c: A.rouge },
    { v: "non", label: "Non",  c: A.sage  },
  ];
  return (
    <div style={{ display: "flex", gap: 10 }}>
      {options.map((o) => {
        const sel = value === o.v;
        return (
          <button key={o.v} onClick={() => onChange(o.v)} style={{
            flex: 1, padding: "18px 12px",
            background: sel ? o.c : A.paper,
            color: sel ? A.white : A.ink,
            border: `1.5px solid ${sel ? o.c : A.ruleSoft}`,
            fontFamily: A.display, fontStyle: "italic", fontSize: 22, fontWeight: 400,
            cursor: "pointer", transition: "all .15s",
            letterSpacing: -0.5,
          }}>
            {o.label}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Type Slider
// ─────────────────────────────────────────────────────────
function SliderOption({ bet, value, onChange }) {
  const v = value != null ? value : bet.defaultValue;
  const hasSet = value != null;
  const formatted = bet.formatValue ? bet.formatValue(v) : `${v} ${bet.suffix || ""}`.trim();
  return (
    <div>
      <div style={{
        textAlign: "center", marginBottom: 18,
        padding: "16px 12px", background: A.paper,
        border: `1.5px solid ${hasSet ? A.rouge : A.ruleSoft}`,
        borderRadius: 4,
      }}>
        <div style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 2, color: A.inkMute, marginBottom: 6, textTransform: "uppercase" }}>
          {hasSet ? "Votre pari" : "Glissez pour parier"}
        </div>
        <div style={{
          fontFamily: A.display, fontStyle: "italic", fontWeight: 700,
          fontSize: 38, color: hasSet ? A.rougeDeep : A.inkMute, letterSpacing: -1, lineHeight: 1,
        }}>
          {formatted}
        </div>
      </div>
      <input
        type="range"
        min={bet.min} max={bet.max} step={bet.step}
        value={v}
        onChange={(e) => onChange(parseInt(e.target.value, 10))}
        style={{
          width: "100%",
          accentColor: A.rouge,
          cursor: "pointer",
        }}
      />
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontFamily: A.mono, fontSize: 10, color: A.inkMute, letterSpacing: 1 }}>
        <span>{bet.labelMin}</span>
        <span>{bet.labelMax}</span>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// ÉCRAN — Récap avant confirmation
// ─────────────────────────────────────────────────────────
function BetsRecap({ bets, name, onCancel, onConfirm }) {
  const formatBetValue = (b, value) => {
    if (value == null || value === "") return "(pas de pari)";
    if (b.type === "slider") return b.formatValue ? b.formatValue(value) : `${value} ${b.suffix || ""}`.trim();
    if (b.type === "yesno") return value === "oui" ? "Oui" : "Non";
    return value;
  };
  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={45} opacity={0.18}/>
      <Page>
        <AppHeader eyebrow="Vérification" title="Vos pronostics" />
        <div style={{ textAlign: "center", fontFamily: A.italic, fontStyle: "italic", fontSize: 16, color: A.inkSoft, marginTop: 6, maxWidth: 460, margin: "8px auto 0", lineHeight: 1.5 }}>
          Une dernière relecture, {name.split(" ")[0]} ? <br/>
          Vous pourrez modifier vos paris jusqu'au <strong style={{ color: A.ink, fontStyle: "normal" }}>1ᵉʳ août 2027</strong>.
        </div>

        <div style={{ marginTop: 28, background: A.card, border: `1px solid ${A.ruleSoft}`, padding: 0 }}>
          {APP_DATA.bets.map((b, i) => {
            const v = bets[b.id];
            const empty = v == null || v === "";
            return (
              <div key={b.id} style={{
                padding: "14px 18px",
                borderTop: i > 0 ? `1px solid ${A.ruleSoft}` : "none",
                opacity: empty ? 0.5 : 1,
              }}>
                <div style={{ display: "flex", gap: 10, alignItems: "baseline" }}>
                  <span style={{ fontFamily: A.mono, fontSize: 10, color: A.inkMute, letterSpacing: 2 }}>{String(i + 1).padStart(2, "0")}</span>
                  <span style={{ color: A.or, fontSize: 14 }}>{b.icon}</span>
                  <span style={{ flex: 1, fontFamily: A.sans, fontSize: 13, color: A.ink, lineHeight: 1.4 }}>{b.q}</span>
                </div>
                <div style={{
                  marginLeft: 32, marginTop: 4,
                  fontFamily: empty ? A.italic : A.display,
                  fontStyle: "italic", fontWeight: empty ? 400 : 700,
                  fontSize: empty ? 13 : 16,
                  color: empty ? A.inkMute : A.rougeDeep, letterSpacing: -0.2,
                }}>
                  {empty ? "— pas de pari" : `→ ${formatBetValue(b, v)}`}
                </div>
              </div>
            );
          })}
        </div>

        <div style={{ display: "flex", gap: 10, marginTop: 24 }}>
          <ButtonA onClick={onCancel}>← Modifier</ButtonA>
          <ButtonA primary onClick={onConfirm} style={{ flex: 1 }}>
            ♠ Confirmer mes paris
          </ButtonA>
        </div>
      </Page>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// ÉCRAN — Soumis (avec Phila easter egg #2)
// ─────────────────────────────────────────────────────────
function BetsSubmitted({ name, bets, philaUnlocked, philaAnswer, onPhilaBet, onModify }) {
  const allSubs = Store.get(BETS_SUBMIT_KEY, []);
  const otherCount = allSubs.filter((s) => s.name.toLowerCase() !== name.toLowerCase()).length;

  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={45} opacity={0.22}/>
      <Page>
        <div style={{ marginTop: 16, textAlign: "center" }}>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Mises enregistrées</div>
          <div style={{
            fontFamily: A.display, fontStyle: "italic", fontWeight: 400,
            fontSize: "clamp(36px, 9vw, 52px)", lineHeight: 0.95,
            color: A.ink, letterSpacing: -1, margin: "8px 0",
          }}>
            Que le sort<br/>vous soit favorable.
          </div>
          <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 16, color: A.inkSoft, marginTop: 10, maxWidth: 400, margin: "10px auto 0", lineHeight: 1.5 }}>
            {name.split(" ")[0]}, vos paris sont scellés. <br/>
            On vérifie le 22 août 2027 — le plus juste gagne une carte unique signée du couple.
          </div>
        </div>

        {/* Stats */}
        <div style={{
          marginTop: 36, padding: "26px 24px", background: A.ink, color: A.white,
          textAlign: "center", position: "relative", overflow: "hidden",
        }}>
          <div style={{ position: "absolute", top: 12, left: 14, color: A.or, fontSize: 16, opacity: 0.4 }}>♥</div>
          <div style={{ position: "absolute", bottom: 12, right: 14, color: A.or, fontSize: 16, opacity: 0.4, transform: "rotate(180deg)" }}>♥</div>
          <div style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 3, color: A.or, marginBottom: 8 }}>VOUS ÊTES</div>
          <div style={{
            fontFamily: A.display, fontStyle: "italic", fontWeight: 700,
            fontSize: 56, lineHeight: 0.9, color: A.or, letterSpacing: -1,
          }}>
            {otherCount + 1}<sup style={{ fontSize: 22 }}>{otherCount === 0 ? "er" : "e"}</sup>
          </div>
          <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: "rgba(255,255,255,0.7)", marginTop: 4 }}>
            à avoir parié sur {otherCount === 0 ? "ces 12 mises" : `${otherCount + 1} participants au total`}
          </div>
        </div>

        {/* Phila secret bet (easter egg #2) */}
        {!philaUnlocked ? (
          <PhilaSecretCard onAnswer={onPhilaBet} />
        ) : (
          <PhilaBadge answer={philaAnswer} />
        )}

        {/* Actions */}
        <div style={{ marginTop: 32, display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
          <ButtonA onClick={onModify}>↺ Modifier mes paris</ButtonA>
        </div>
      </Page>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Carte secrète Phila (easter egg #2)
// ─────────────────────────────────────────────────────────
function PhilaSecretCard({ onAnswer }) {
  const [expanded, setExpanded] = React.useState(false);
  const bet = APP_DATA.philaSecretBet;
  return (
    <div style={{ marginTop: 28 }}>
      {!expanded ? (
        <button onClick={() => setExpanded(true)} style={{
          width: "100%", padding: "20px 22px",
          background: `linear-gradient(135deg, ${A.ink} 0%, #2A2620 100%)`,
          color: A.white, border: `1.5px solid ${A.or}`, cursor: "pointer",
          textAlign: "left", borderRadius: 4,
          display: "flex", alignItems: "center", gap: 16,
          transition: "transform .15s",
        }} onMouseEnter={(e) => e.currentTarget.style.transform = "translateY(-2px)"} onMouseLeave={(e) => e.currentTarget.style.transform = "translateY(0)"}>
          <div style={{
            width: 46, height: 46, borderRadius: "50%",
            background: A.or + "22", border: `1.5px solid ${A.or}`,
            display: "flex", alignItems: "center", justifyContent: "center",
            flexShrink: 0,
          }}><Phila variant="head" size={32} /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 2.5, color: A.or, marginBottom: 4 }}>
              PARI SECRET DÉCOUVERT
            </div>
            <div style={{ fontFamily: A.display, fontStyle: "italic", fontSize: 19, color: A.white, lineHeight: 1.2 }}>
              Phila vous a laissé un message.
            </div>
          </div>
          <div style={{ color: A.or, fontFamily: A.display, fontSize: 22 }}>→</div>
        </button>
      ) : (
        <div className="anim-up" style={{
          background: `linear-gradient(135deg, ${A.ink} 0%, #2A2620 100%)`,
          color: A.white, padding: "26px 24px", borderRadius: 4,
          border: `1.5px solid ${A.or}`,
        }}>
          <div style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 2.5, color: A.or, marginBottom: 12 }}>
            <Phila variant="head" size={14} style={{ marginRight: 6, verticalAlign: "-3px" }} />PARI SECRET · CLUB PHILA
          </div>
          <div style={{
            fontFamily: A.display, fontStyle: "italic",
            fontSize: 20, lineHeight: 1.25, color: A.white,
            marginBottom: 20, textWrap: "balance",
          }}>
            {bet.q}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {bet.options.map((opt) => (
              <button key={opt} onClick={() => onAnswer(opt)} style={{
                textAlign: "left", padding: "12px 16px",
                background: "rgba(255,255,255,0.06)",
                color: A.white,
                border: `1.5px solid rgba(255,255,255,0.15)`,
                fontFamily: A.sans, fontSize: 13.5,
                cursor: "pointer", transition: "all .15s",
              }} onMouseEnter={(e) => { e.currentTarget.style.background = A.or; e.currentTarget.style.color = A.ink; }}
                 onMouseLeave={(e) => { e.currentTarget.style.background = "rgba(255,255,255,0.06)"; e.currentTarget.style.color = A.white; }}>
                {opt}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function PhilaBadge({ answer }) {
  return (
    <div className="anim-up" style={{
      marginTop: 28, background: A.or, padding: "22px 22px",
      border: `1px solid ${A.orDeep}`, borderRadius: 4, textAlign: "center",
    }}>
      <Phila variant="wide" size={72} style={{ display: "block", margin: "0 auto 10px" }} />
      <div className="display-bold" style={{ fontSize: 22, color: A.ink, marginBottom: 6 }}>
        Pari Phila enregistré
      </div>
      <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.ink, lineHeight: 1.5, maxWidth: 320, margin: "0 auto" }}>
        "{answer}"
      </div>
      <div style={{ marginTop: 14, fontFamily: A.mono, fontSize: 9, letterSpacing: 2, color: A.orDeep }}>
        ♥ MEMBRE DU CLUB PHILA ♥
      </div>
    </div>
  );
}

Object.assign(window, { BetsPage });
