// ===== Teuanjai Radio — Login + Browser Guard =====

// Brand mark — glass disc with EQ glyph (geometric only)
function BrandMark({ size = 84 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: "30%",
      background: "linear-gradient(140deg, oklch(0.74 0.12 230), oklch(0.78 0.11 185), oklch(0.80 0.10 160))",
      display: "grid", placeItems: "center", position: "relative", overflow: "hidden",
      boxShadow: "0 16px 36px oklch(0.6 0.12 220 / 0.36), inset 0 1px 2px rgba(255,255,255,.6)",
    }}>
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(120% 80% at 30% 0%, rgba(255,255,255,.5), transparent 55%)" }} />
      <EQ playing bars={5} h={Math.round(size*0.36)} w={Math.round(size*0.06)} gap={Math.round(size*0.055)} color="rgba(255,255,255,.95)" />
    </div>
  );
}

// In-app browser overlay
function BrowserGuard({ appName, onDismiss }) {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    const url = window.location.href;
    if (navigator.clipboard) navigator.clipboard.writeText(url).then(() => setCopied(true)).catch(() => setCopied(true));
    else setCopied(true);
    setTimeout(() => setCopied(false), 2200);
  };
  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 50, display: "flex", flexDirection: "column",
      alignItems: "center", justifyContent: "center", padding: 28, textAlign: "center",
      background: "oklch(0.95 0.03 215 / 0.55)", backdropFilter: "blur(8px)" }}>
      <div className="glass" style={{ borderRadius: 28, padding: "30px 24px", maxWidth: 340, animation: "pop 0.4s both" }}>
        <div style={{ width: 64, height: 64, borderRadius: 20, margin: "0 auto 16px", display: "grid", placeItems: "center",
          background: "linear-gradient(140deg, oklch(0.78 0.10 230), oklch(0.80 0.10 165))", color: "#fff" }}>
          <Icon name="globe" size={32} />
        </div>
        <h2 style={{ margin: "0 0 8px", fontFamily: "var(--font-disp)", fontSize: 19, color: "var(--ink)" }}>เปิดในเบราว์เซอร์</h2>
        <p style={{ margin: "0 0 18px", fontSize: 14, lineHeight: 1.6, color: "var(--ink-soft)" }}>
          คุณกำลังเปิดผ่าน{appName ? " " + appName : "แอปอื่น"} เพื่อให้ระบบทำงานสมบูรณ์
          กรุณาเปิดใน <b>Chrome</b> หรือ <b>Safari</b><br/>
          <span style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>(แตะ ··· มุมขวาบน → “เปิดในเบราว์เซอร์”)</span>
        </p>
        <button onClick={onDismiss} style={btnPrimary}>เข้าร่วมสตรีม</button>
        <button onClick={copy} style={{ ...btnGhost, marginTop: 10 }}>{copied ? "คัดลอกลิงก์แล้ว ✓" : "คัดลอกลิงก์"}</button>
      </div>
    </div>
  );
}

// OTP-style 3-digit numeric input
function CodeInput({ value, onChange, onComplete }) {
  const refs = [useRef(null), useRef(null), useRef(null)];
  const set = (i, v) => {
    const digit = v.replace(/\D/g, "").slice(-1);
    const arr = value.split("");
    arr[i] = digit || "";
    const next = arr.join("").slice(0, 3);
    onChange(next);
    if (digit && i < 2) refs[i + 1].current && refs[i + 1].current.focus();
    if (next.length === 3 && !next.includes("") && onComplete) setTimeout(onComplete, 120);
  };
  const onKey = (i, e) => {
    if (e.key === "Backspace" && !value[i] && i > 0) refs[i - 1].current && refs[i - 1].current.focus();
  };
  return (
    <div style={{ display: "flex", gap: 14, justifyContent: "center" }}>
      {[0, 1, 2].map((i) => {
        const filled = !!value[i];
        return (
          <input
            key={i} ref={refs[i]} value={value[i] || ""} inputMode="numeric" pattern="[0-9]*" maxLength={1}
            onChange={(e) => set(i, e.target.value)} onKeyDown={(e) => onKey(i, e)}
            onFocus={(e) => e.target.select()}
            aria-label={"หลักที่ " + (i + 1)}
            style={{
              width: 62, height: 74, textAlign: "center", fontSize: 30, fontWeight: 600,
              fontFamily: "var(--font-disp)", color: "var(--ink)",
              borderRadius: 20, outline: "none",
              background: filled ? "oklch(1 0 0 / 0.85)" : "oklch(1 0 0 / 0.5)",
              border: "1.5px solid " + (filled ? "oklch(0.70 0.12 215 / 0.8)" : "var(--glass-line)"),
              boxShadow: filled ? "0 8px 22px oklch(0.6 0.12 215 / 0.22), inset 0 1px 2px rgba(255,255,255,.7)" : "var(--shadow-sm)",
              transition: "all 0.22s cubic-bezier(0.22,1,0.36,1)",
            }}
          />
        );
      })}
    </div>
  );
}

function LoginScreen({ onCheckIn }) {
  const [code, setCode] = useState("");
  const [shake, setShake] = useState(false);
  const member = code.length === 3 ? memberFromCode(code) : null;
  const known = code.length === 3 && !!MEMBERS[code];

  const submit = () => {
    if (code.length !== 3) {
      setShake(true); setTimeout(() => setShake(false), 480); return;
    }
    onCheckIn(code, memberFromCode(code));
  };

  return (
    <div className="screen scroll" style={{ padding: "0 26px", justifyContent: "center" }}>
      <div style={{ flex: "0 0 auto", display: "flex", flexDirection: "column", alignItems: "center", gap: 0, paddingBottom: 14 }}>
        <BrandMark size={88} />
        <h1 style={{ margin: "22px 0 4px", fontFamily: "var(--font-disp)", fontSize: 27, fontWeight: 700, letterSpacing: "-0.01em", color: "var(--ink)" }}>
          Teuanjai <span style={{ color: "var(--accent)" }}>Radio</span>
        </h1>
        <p style={{ margin: 0, fontSize: 14, color: "var(--ink-soft)", textAlign: "center" }}>ระบบบันทึกเวลาเข้าร่วมกิจกรรม</p>

        <div className="glass" style={{ marginTop: 26, width: "100%", borderRadius: "var(--radius)", padding: "26px 22px",
          animation: shake ? "shake 0.45s" : "none" }}>
          <div style={{ textAlign: "center", marginBottom: 18 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink-soft)", marginBottom: 4 }}>กรอกรหัสสาขา</div>
            <div style={{ fontSize: 12, color: "var(--ink-faint)" }}>ตัวเลข 3 หลัก</div>
          </div>

          <CodeInput value={code} onChange={setCode} onComplete={() => {}} />

          {/* live identity preview */}
          <div style={{ height: 26, marginTop: 16, display: "flex", alignItems: "center", justifyContent: "center", gap: 7,
            opacity: member ? 1 : 0, transform: member ? "none" : "translateY(4px)", transition: "all 0.3s" }}>
            <span style={{ color: known ? "var(--accent-3)" : "var(--ink-faint)", display: "inline-flex" }}>
              <Icon name={known ? "check" : "user"} size={16} />
            </span>
            <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>{member || ""}</span>
          </div>

          <button onClick={submit} style={{ ...btnPrimary, marginTop: 6, opacity: code.length === 3 ? 1 : 0.55 }}>
            ยืนยันเข้าร่วม
          </button>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 18, fontSize: 12, color: "var(--ink-faint)" }}>
          <Icon name="spark" size={13} />
          <span>รหัสสาขาตัวอย่าง: 000 · 001 · 123</span>
        </div>
      </div>
    </div>
  );
}

const btnPrimary = {
  width: "100%", height: 54, borderRadius: 18, color: "#fff", fontSize: 16, fontWeight: 600,
  fontFamily: "var(--font-body)",
  background: "linear-gradient(120deg, oklch(0.66 0.13 232), oklch(0.71 0.12 198) 55%, oklch(0.73 0.11 165))",
  boxShadow: "0 12px 26px oklch(0.6 0.12 215 / 0.36), inset 0 1px 1px rgba(255,255,255,.4)",
  transition: "transform 0.15s, opacity 0.2s",
};
const btnGhost = {
  width: "100%", height: 46, borderRadius: 16, fontSize: 14.5, fontWeight: 600, color: "var(--ink-soft)",
  background: "oklch(1 0 0 / 0.5)", border: "1px solid var(--glass-line)",
};

// shake keyframe
(function(){ if(document.getElementById("tj-shake"))return; const s=document.createElement("style"); s.id="tj-shake";
  s.textContent="@keyframes shake{0%,100%{transform:translateX(0)}20%{transform:translateX(-8px)}40%{transform:translateX(7px)}60%{transform:translateX(-5px)}80%{transform:translateX(4px)}}";
  document.head.appendChild(s); })();

Object.assign(window, { LoginScreen, BrowserGuard, BrandMark, btnPrimary, btnGhost });
