/* Vito's Wings — Mi Cuenta / My Account screen
   Mocks WhatsApp OTP login + logged-in customer dashboard. */

function ScreenAccount({ lang, goto }) {
  const [authStep, setAuthStep] = useState(() => {
    return localStorage.getItem("vw_account") ? "in" : "phone";
  });
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [otpSent, setOtpSent] = useState(false);

  function sendOTP(e) {
    e?.preventDefault();
    if (!phone || phone.length < 8) return;
    setOtpSent(true);
    setAuthStep("otp");
  }
  function verify(e) {
    e?.preventDefault();
    if (code.length !== 6) return;
    localStorage.setItem("vw_account", JSON.stringify({ phone, name: "Andrea M." }));
    setAuthStep("in");
  }
  function logout() {
    localStorage.removeItem("vw_account");
    setPhone(""); setCode(""); setOtpSent(false);
    setAuthStep("phone");
  }

  if (authStep === "in") return <AccountDashboard lang={lang} logout={logout} goto={goto} />;

  // ============== LOGIN FLOW ==============
  return (
    <section style={{ padding: "60px 6vw 100px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40, minHeight: "70vh" }} className="vw-2col">
      <div>
        <SectionHeader
          kicker={lang === "es" ? "Mi Cuenta" : "My Account"}
          title={lang === "es" ? "Entra con tu WhatsApp." : "Sign in with WhatsApp."}
          sub={lang === "es" ? "Sin contraseñas. Sin emails de spam. Solo tu número, un código rápido, y dentro." : "No passwords. No spam emails. Just your number, a quick code, and you're in."}
        />

        {authStep === "phone" && (
          <form onSubmit={sendOTP} style={{ display: "flex", flexDirection: "column", gap: 14, maxWidth: 420 }}>
            <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <span style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.2em" }}>{lang === "es" ? "WHATSAPP" : "WHATSAPP"}</span>
              <input
                required type="tel" placeholder="+504 ____-____"
                value={phone} onChange={e => setPhone(e.target.value)}
                style={{ border: "2px solid #0A0A0A", padding: "16px 18px", background: "#F6F4EF", fontFamily: "'DM Sans', sans-serif", fontSize: 18, boxShadow: "4px 4px 0 #0A0A0A" }}
                autoFocus
              />
            </label>
            <PrimaryBtn big full type="submit">{lang === "es" ? "ENVIAR CÓDIGO →" : "SEND CODE →"}</PrimaryBtn>
            <div style={{ fontSize: 12, color: "rgba(10,10,10,0.55)", textAlign: "center", marginTop: 8, lineHeight: 1.5 }}>
              {lang === "es" ? "Te llegará un código de 6 dígitos por WhatsApp en 5 segundos." : "You'll get a 6-digit code via WhatsApp in 5 seconds."}
            </div>
          </form>
        )}

        {authStep === "otp" && (
          <form onSubmit={verify} style={{ display: "flex", flexDirection: "column", gap: 14, maxWidth: 420 }}>
            <div style={{ background: "#0A0A0A", color: "#F6F4EF", padding: 16, marginBottom: 6, display: "flex", gap: 12, alignItems: "center" }}>
              <span style={{ fontSize: 24 }}>💬</span>
              <div style={{ fontSize: 13, lineHeight: 1.5 }}>
                <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.14em", color: "#E63426" }}>WHATSAPP</div>
                <div>{lang === "es" ? "Código enviado a " : "Code sent to "}<b>{phone}</b></div>
              </div>
            </div>
            <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <span style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.2em" }}>{lang === "es" ? "CÓDIGO DE 6 DÍGITOS" : "6-DIGIT CODE"}</span>
              <input
                required inputMode="numeric" maxLength={6} placeholder="• • • • • •"
                value={code} onChange={e => setCode(e.target.value.replace(/\D/g, ""))}
                style={{ border: "2px solid #0A0A0A", padding: "16px 18px", background: "#F6F4EF", fontFamily: "'Anton', sans-serif", fontSize: 42, letterSpacing: "0.4em", textAlign: "center", boxShadow: "4px 4px 0 #0A0A0A" }}
                autoFocus
              />
            </label>
            <div style={{ fontSize: 12, color: "rgba(10,10,10,0.6)", padding: "10px 14px", border: "1px dashed rgba(10,10,10,0.3)", background: "rgba(230,52,38,0.05)" }}>
              💡 <i>{lang === "es" ? "Demo: pon cualquier 6 dígitos (ej. 248391)" : "Demo: type any 6 digits (e.g. 248391)"}</i>
            </div>
            <PrimaryBtn big full type="submit">{lang === "es" ? "ENTRAR →" : "ENTER →"}</PrimaryBtn>
            <button type="button" onClick={() => setAuthStep("phone")} style={{ appearance: "none", border: 0, background: "transparent", color: "rgba(10,10,10,0.55)", fontSize: 12, letterSpacing: "0.16em", cursor: "pointer", padding: 6 }}>
              ← {lang === "es" ? "USAR OTRO NÚMERO" : "USE A DIFFERENT NUMBER"}
            </button>
          </form>
        )}
      </div>

      {/* Why side panel */}
      <aside style={{ background: "#0A0A0A", color: "#F6F4EF", padding: 32, alignSelf: "start", position: "relative" }}>
        <div style={{ position: "absolute", top: -10, right: -10, background: "#E63426", color: "#F6F4EF", padding: "6px 10px", fontFamily: "'Anton', sans-serif", fontSize: 12, letterSpacing: "0.14em", transform: "rotate(5deg)", boxShadow: "3px 3px 0 #F6F4EF" }}>
          {lang === "es" ? "GRATIS" : "FREE"}
        </div>
        <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.22em", color: "#E63426" }}>▌ {lang === "es" ? "POR QUÉ CREAR CUENTA" : "WHY MAKE AN ACCOUNT"}</div>
        <h3 style={{ fontFamily: "'Anton', sans-serif", fontSize: 36, lineHeight: 0.9, margin: "12px 0 0", letterSpacing: "-0.005em" }}>{lang === "es" ? "PARA PEDIR EN 3 TAPS." : "ORDER IN 3 TAPS."}</h3>

        <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 16 }}>
          {[
            { ic: "★", t_en: "Earn Vito's Club stamps", t_es: "Acumula estampas Vito's Club", d_en: "1 stamp per order. 10 stamps = a free round.", d_es: "1 estampa por orden. 10 estampas = ronda gratis." },
            { ic: "↻", t_en: "Reorder your favorites", t_es: "Repite tus favoritos", d_en: "We remember your usuals. Tap once to reorder.", d_es: "Recordamos tus favoritos. Un tap para repetir." },
            { ic: "🐶", t_en: "AI-personalized rewards", t_es: "Recompensas personalizadas", d_en: "We predict what you'll love. You get that, not generic stuff.", d_es: "Predecimos lo que te encantará. Recibís eso, no algo genérico." },
            { ic: "📍", t_en: "Saved details", t_es: "Datos guardados", d_en: "Phone, payment, pickup time — set once.", d_es: "Teléfono, pago, hora de recogida — una sola vez." },
          ].map((b, i) => (
            <div key={i} style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
              <div style={{ width: 36, height: 36, border: "1px solid rgba(246,244,239,0.4)", display: "flex", alignItems: "center", justifyContent: "center", color: "#E63426", fontSize: 18, flexShrink: 0 }}>{b.ic}</div>
              <div>
                <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 16, letterSpacing: "0.06em" }}>{b["t_" + lang].toUpperCase()}</div>
                <div style={{ fontSize: 13, color: "rgba(246,244,239,0.7)", marginTop: 2, lineHeight: 1.5 }}>{b["d_" + lang]}</div>
              </div>
            </div>
          ))}
        </div>
      </aside>
    </section>
  );
}

// ============== LOGGED-IN DASHBOARD ==============
function AccountDashboard({ lang, logout, goto }) {
  const account = JSON.parse(localStorage.getItem("vw_account") || "{}");
  const [stamps, setStamps] = useState(() => parseInt(localStorage.getItem("vw_stamps") || "7", 10));
  useEffect(() => { localStorage.setItem("vw_stamps", String(stamps)); }, [stamps]);

  // Mock history
  const history = [
    { d: "Mar 14",  items: "Vito's Para Dos · Lemon Pepper + Hot Honey", price: 540, status: "delivered" },
    { d: "Mar 09",  items: "Boneless 9 · Hot Honey · Limonada Menta",     price: 360, status: "delivered" },
    { d: "Mar 02",  items: "Vito's Burger × 2 · Loaded Fries",             price: 705, status: "delivered" },
    { d: "Feb 24",  items: "Wings 12 · Buffalo · Pepsi",                   price: 380, status: "delivered" },
  ];

  return (
    <section style={{ padding: "40px 6vw 80px" }}>
      {/* Welcome header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 32, borderBottom: "2px solid #0A0A0A", paddingBottom: 24, gap: 20, flexWrap: "wrap" }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: "0.22em", color: "#E63426", fontWeight: 700 }}>▌ {lang === "es" ? "HOLA DE NUEVO" : "WELCOME BACK"}</div>
          <h2 style={{ fontFamily: "'Anton', sans-serif", fontSize: "clamp(40px, 6vw, 84px)", lineHeight: 0.9, margin: "8px 0 0", letterSpacing: "-0.01em" }}>{(account.name || "AMIGO").toUpperCase()}.</h2>
          <div style={{ fontSize: 13, color: "rgba(10,10,10,0.55)", marginTop: 8, letterSpacing: "0.12em" }}>{account.phone} · MEMBER #00342</div>
        </div>
        <button onClick={logout} style={{
          appearance: "none", border: "1px solid #0A0A0A", background: "transparent",
          padding: "10px 14px", fontFamily: "'Anton', sans-serif",
          fontSize: 12, letterSpacing: "0.16em", cursor: "pointer",
        }}>{lang === "es" ? "CERRAR SESIÓN ↗" : "SIGN OUT ↗"}</button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 32 }} className="vw-2col">
        {/* VITO'S CLUB CARD */}
        <div style={{ background: "#0A0A0A", color: "#F6F4EF", padding: 28, position: "relative", overflow: "hidden", boxShadow: "10px 10px 0 #E63426" }}>
          <div style={{ position: "absolute", top: -10, right: -10, opacity: 0.06 }}>
            <img src="assets/vitos-icon.png" alt="" style={{ height: 240, filter: "invert(1)" }} />
          </div>
          <div style={{ position: "relative", zIndex: 1 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div>
                <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.22em", color: "#E63426" }}>VITO'S CLUB · MEMBER #00342</div>
                <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 48, lineHeight: 0.9, marginTop: 8 }}>WING CARD</div>
              </div>
              <div style={{ background: "#F6F4EF", color: "#0A0A0A", padding: 4 }}>
                {/* Mock QR */}
                <div style={{ width: 72, height: 72, background: "repeating-linear-gradient(0deg, #0A0A0A 0 4px, #F6F4EF 4px 8px), repeating-linear-gradient(90deg, #0A0A0A 0 4px, transparent 4px 8px)", backgroundBlendMode: "multiply" }} />
                <div style={{ fontSize: 7, letterSpacing: "0.14em", textAlign: "center", marginTop: 2 }}>SCAN</div>
              </div>
            </div>

            <div style={{ marginTop: 22, display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 8 }}>
              {Array(10).fill(0).map((_, i) => (
                <div key={i} style={{
                  aspectRatio: "1/1",
                  border: "2px " + (i < stamps ? "solid #E63426" : "dashed rgba(246,244,239,0.4)"),
                  background: i < stamps ? "#E63426" : "transparent",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontFamily: "'Anton', sans-serif", fontSize: 22,
                  transition: "all 0.25s",
                }}>{i < stamps ? "★" : i + 1}</div>
              ))}
            </div>

            <div style={{ marginTop: 18, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div>
                <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 28, color: "#E63426", lineHeight: 1 }}>{stamps}/10</div>
                <div style={{ fontSize: 10, opacity: 0.7, letterSpacing: "0.18em", marginTop: 4 }}>{lang === "es" ? `FALTAN ${10 - stamps} ESTAMPAS` : `${10 - stamps} STAMPS TO GO`}</div>
              </div>
              <button onClick={() => setStamps(s => Math.min(10, s + 1))} style={{
                appearance: "none", border: "1px solid #F6F4EF", background: "transparent",
                color: "#F6F4EF", padding: "10px 14px", fontFamily: "'Anton', sans-serif",
                fontSize: 11, letterSpacing: "0.14em", cursor: "pointer",
              }}>+ {lang === "es" ? "DEMO STAMP" : "DEMO STAMP"}</button>
            </div>

            {stamps >= 10 && (
              <div style={{ marginTop: 14, background: "#E63426", padding: "12px 14px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span style={{ fontFamily: "'Anton', sans-serif", fontSize: 16, letterSpacing: "0.08em" }}>🎉 {lang === "es" ? "RECOMPENSA LISTA" : "REWARD READY"}</span>
                <button onClick={() => setStamps(0)} style={{ background: "#0A0A0A", color: "#F6F4EF", border: 0, padding: "6px 10px", fontFamily: "'Anton', sans-serif", letterSpacing: "0.1em", fontSize: 11, cursor: "pointer" }}>{lang === "es" ? "CANJEAR" : "REDEEM"}</button>
              </div>
            )}
          </div>
        </div>

        {/* AI PREDICTION */}
        <div style={{ background: "#F1ECDD", border: "2px solid #0A0A0A", padding: 24, position: "relative" }} className="vw-halftone">
          <div style={{ background: "#F1ECDD", padding: "0", position: "relative", zIndex: 1 }}>
            <div style={{ fontSize: 10, letterSpacing: "0.22em", color: "rgba(10,10,10,0.6)", fontWeight: 700 }}>▌ AI · {lang === "es" ? "PREDICCIÓN PERSONAL" : "PERSONAL PREDICTION"}</div>
            <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 22, marginTop: 8, lineHeight: 1.1 }}>{lang === "es" ? "TU PRÓXIMA RECOMPENSA" : "YOUR NEXT REWARD"}</div>
            <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 32, marginTop: 4, color: "#E63426", lineHeight: 1 }}>6 BONELESS · HOT HONEY</div>
            <div style={{ marginTop: 8, fontSize: 12, color: "rgba(10,10,10,0.7)", lineHeight: 1.5 }}>
              {lang === "es"
                ? "Tu combo más pedido en los últimos 60 días. Cuando completes tu tarjeta, esa es la ronda que va por la casa."
                : "Your most-ordered combo in the last 60 days. When you fill your card, this one's on us."}
            </div>
            <div style={{ display: "flex", gap: 4, alignItems: "center", marginTop: 12 }}>
              {Array(5).fill(0).map((_, i) => <span key={i} style={{ color: i < 4 ? "#E63426" : "rgba(10,10,10,0.2)", fontSize: 14 }}>★</span>)}
              <span style={{ fontSize: 11, marginLeft: 4, color: "rgba(10,10,10,0.6)" }}>92% {lang === "es" ? "confianza" : "confidence"}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Quick reorder */}
      <div style={{ marginTop: 48 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16, borderBottom: "1px solid #0A0A0A", paddingBottom: 10 }}>
          <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 28, letterSpacing: "0.04em" }}>{lang === "es" ? "PEDIR DE NUEVO" : "REORDER"}</div>
          <button onClick={() => goto("menu")} style={{ appearance: "none", border: 0, background: "transparent", fontSize: 12, letterSpacing: "0.18em", color: "#E63426", cursor: "pointer", fontWeight: 700 }}>
            {lang === "es" ? "VER MENÚ →" : "BROWSE MENU →"}
          </button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 14 }}>
          {[
            { name: "Vito's Para Dos", sub: "Lemon Pepper + Hot Honey", p: 540, times: 8 },
            { name: "Boneless 9 + Limonada", sub: "Hot Honey", p: 360, times: 6 },
            { name: "Vito's Burger × 2", sub: lang === "es" ? "Sin cebolla" : "No onion", p: 560, times: 4 },
          ].map((f, i) => (
            <button key={i} onClick={() => goto("menu")} style={{
              appearance: "none", border: "1px solid #0A0A0A", background: "#F6F4EF",
              textAlign: "left", padding: 16, cursor: "pointer",
              display: "flex", flexDirection: "column", gap: 6, position: "relative",
              transition: "transform 0.15s, box-shadow 0.15s",
            }}
              onMouseEnter={e => { e.currentTarget.style.transform = "translate(-2px,-2px)"; e.currentTarget.style.boxShadow = "5px 5px 0 #0A0A0A"; }}
              onMouseLeave={e => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; }}
            >
              <div style={{ position: "absolute", top: 10, right: 10, background: "#E63426", color: "#F6F4EF", padding: "2px 6px", fontFamily: "'Anton', sans-serif", fontSize: 11, letterSpacing: "0.06em" }}>×{f.times}</div>
              <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 20, letterSpacing: "0.02em" }}>{f.name.toUpperCase()}</div>
              <div style={{ fontSize: 12, color: "rgba(10,10,10,0.65)" }}>{f.sub}</div>
              <div style={{ marginTop: "auto", paddingTop: 8, display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: "1px dashed rgba(10,10,10,0.25)" }}>
                <span style={{ fontFamily: "'Anton', sans-serif", fontSize: 18, color: "#E63426" }}>{fmtL(f.p)}</span>
                <span style={{ fontSize: 11, letterSpacing: "0.14em", color: "#E63426", fontWeight: 700 }}>{lang === "es" ? "AGREGAR →" : "ADD →"}</span>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Order history */}
      <div style={{ marginTop: 48 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16, borderBottom: "1px solid #0A0A0A", paddingBottom: 10 }}>
          <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 28, letterSpacing: "0.04em" }}>{lang === "es" ? "HISTORIAL" : "HISTORY"}</div>
          <div style={{ fontSize: 12, letterSpacing: "0.16em", color: "rgba(10,10,10,0.55)" }}>{history.length} {lang === "es" ? "ÓRDENES" : "ORDERS"}</div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
          {history.map((h, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "70px 1fr auto auto", gap: 16, padding: "16px 0", borderBottom: i < history.length - 1 ? "1px dashed rgba(10,10,10,0.2)" : "none", alignItems: "center" }}>
              <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 18, color: "#E63426", letterSpacing: "0.04em" }}>{h.d}</div>
              <div style={{ fontSize: 14, lineHeight: 1.4 }}>{h.items}</div>
              <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 18, letterSpacing: "0.04em" }}>{fmtL(h.price)}</div>
              <button onClick={() => goto("menu")} style={{ appearance: "none", border: "1px solid #0A0A0A", background: "transparent", padding: "8px 12px", fontFamily: "'Anton', sans-serif", fontSize: 11, letterSpacing: "0.14em", cursor: "pointer" }}>
                ↻ {lang === "es" ? "REPETIR" : "REORDER"}
              </button>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

window.ScreenAccount = ScreenAccount;
