/* global React, firebase, Icon, kAuth, kDb, printSlipWithQR */
const { useState, useEffect, useRef } = React;

// ─── Helpers ───────────────────────────────────────────────────────────────

function friendlyError(code) {
  switch (code) {
    case "auth/user-not-found":
    case "auth/wrong-password":
    case "auth/invalid-credential":   return "អ៊ីមែល ឬ លេខសម្ងាត់មិនត្រឹមត្រូវ · Invalid email or password";
    case "auth/email-already-in-use": return "អ៊ីមែលនេះបានប្រើហើយ · Email already in use";
    case "auth/weak-password":        return "លេខសម្ងាត់ខ្សោយ · Password too weak (min 6 chars)";
    case "auth/invalid-email":        return "អ៊ីមែលមិនត្រឹមត្រូវ · Invalid email format";
    case "auth/too-many-requests":    return "សាកល្បងម្ដងទៀតពេលក្រោយ · Too many attempts, try again later";
    case "auth/popup-blocked":        return "Popup ត្រូវបានទប់ · Allow popups for this site and try again";
    case "auth/account-exists-with-different-credential":
                                      return "អ៊ីមែលនេះប្រើវិធីចូលផ្សេង · This email uses a different sign-in method";
    case "auth/invalid-phone-number": return "លេខទូរស័ព្ទមិនត្រឹមត្រូវ · Invalid phone number (use +855 format)";
    case "auth/missing-phone-number": return "សូមបញ្ចូលលេខទូរស័ព្ទ · Please enter your phone number";
    case "auth/invalid-verification-code": return "លេខកូដមិនត្រឹមត្រូវ · Incorrect verification code";
    case "auth/code-expired":         return "លេខកូដផុតកំណត · Code expired, please resend";
    case "auth/missing-verification-code": return "សូមបញ្ចូលលេខកូដ · Please enter the 6-digit code";
    case "auth/quota-exceeded":       return "SMS ហួសដែន · SMS quota exceeded, try again later";
    default:                          return "មានបញ្ហា · Something went wrong. Try again.";
  }
}

// Google logo mark (coloured SVG, inline — no icon library needed)
function GoogleMark() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z" fill="#4285F4"/>
      <path d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z" fill="#34A853"/>
      <path d="M3.964 10.707A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.707V4.961H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.039l3.007-2.332z" fill="#FBBC05"/>
      <path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.96L3.964 7.293C4.672 5.163 6.656 3.58 9 3.58z" fill="#EA4335"/>
    </svg>
  );
}

// ─── Reusable Field ────────────────────────────────────────────────────────

function Field({ label, type = "text", value, onChange, placeholder, required, disabled }) {
  const fieldId = label.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase().slice(0, 24);
  return (
    <div className="col gap-6">
      <label htmlFor={fieldId} style={{
        fontSize: "var(--text-2xs)", fontFamily: "var(--font-mono)",
        letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--fg-muted)"
      }}>
        {label}
      </label>
      <input
        id={fieldId}
        type={type}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        required={required}
        disabled={disabled}
        style={{
          width: "100%", padding: "12px 14px",
          background: disabled ? "var(--bg-3)" : "var(--bg-2)",
          border: "1px solid var(--line-strong)",
          borderRadius: "var(--radius)", font: "inherit",
          fontSize: "var(--text-base)", color: "var(--fg)",
          outline: "none", boxSizing: "border-box",
          opacity: disabled ? 0.6 : 1, cursor: disabled ? "not-allowed" : "text",
          transition: "border-color 140ms ease"
        }}
        onFocus={e  => { if (!disabled) e.target.style.borderColor = "var(--accent)"; }}
        onBlur={e   => { e.target.style.borderColor = "var(--line-strong)"; }}
      />
    </div>
  );
}

// ─── Loading spinner ───────────────────────────────────────────────────────

function LoadingSpinner() {
  return (
    <main style={{ padding: "120px 0", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div role="status" aria-label="Loading…" className="col gap-16 items-center">
        <div style={{
          width: 40, height: 40, borderRadius: "50%",
          border: "2px solid var(--line-strong)", borderTopColor: "var(--accent)",
          animation: "ks-spin 0.8s linear infinite"
        }} />
        <span className="km-sans text-muted" style={{ fontSize: "var(--text-sm)" }}>កំពុងផ្ទុក…</span>
      </div>
    </main>
  );
}

// ─── Auth screen (sign-in / register / phone) ─────────────────────────────

function AuthScreen() {
  const [tab,  setTab]  = useState("login");
  const [form, setForm] = useState({ name: "", email: "", phone: "", password: "", confirm: "" });
  const [error,   setError]   = useState("");
  const [loading, setLoading] = useState(false);

  // Phone-specific state
  const [phoneNum,      setPhoneNum]      = useState("");
  const [otp,           setOtp]           = useState("");
  const [phoneStep,     setPhoneStep]     = useState(1); // 1 = enter number, 2 = enter OTP
  const [confirmResult, setConfirmResult] = useState(null);
  const recaptchaContainerRef = useRef(null);
  const recaptchaVerifierRef  = useRef(null);

  // Clean up reCAPTCHA when leaving phone tab
  useEffect(() => {
    if (tab !== "phone") {
      recaptchaVerifierRef.current?.clear();
      recaptchaVerifierRef.current = null;
      setPhoneStep(1);
      setPhoneNum("");
      setOtp("");
      setConfirmResult(null);
    }
    setError("");
  }, [tab]);

  const set = k => e => setForm(prev => ({ ...prev, [k]: e.target.value }));

  const login = async e => {
    e.preventDefault();
    setError(""); setLoading(true);
    try {
      await kAuth.signInWithEmailAndPassword(form.email, form.password);
    } catch (err) {
      setError(friendlyError(err.code));
    } finally { setLoading(false); }
  };

  const googleSignIn = async () => {
    setError(""); setLoading(true);
    try {
      const provider = new firebase.auth.GoogleAuthProvider();
      const cred = await kAuth.signInWithPopup(provider);
      const ref = kDb.collection("users").doc(cred.user.uid);
      const snap = await ref.get();
      if (!snap.exists) {
        await ref.set({
          name:        cred.user.displayName || "",
          email:       cred.user.email || "",
          phone:       cred.user.phoneNumber || "",
          address:     "",
          memberSince: firebase.firestore.FieldValue.serverTimestamp()
        });
      }
    } catch (err) {
      if (err.code !== "auth/popup-closed-by-user") setError(friendlyError(err.code));
    } finally { setLoading(false); }
  };

  const register = async e => {
    e.preventDefault();
    setError("");
    if (form.password !== form.confirm) { setError("លេខសម្ងាត់មិនដូចគ្នា · Passwords don't match"); return; }
    if (form.password.length < 6) { setError("លេខសម្ងាត់ត្រូវការយ៉ាងតិច ៦ តួ · Min 6 characters"); return; }
    setLoading(true);
    try {
      const cred = await kAuth.createUserWithEmailAndPassword(form.email, form.password);
      await cred.user.updateProfile({ displayName: form.name });
      await kDb.collection("users").doc(cred.user.uid).set({
        name:        form.name,
        email:       form.email,
        phone:       form.phone,
        address:     "",
        memberSince: firebase.firestore.FieldValue.serverTimestamp()
      });
    } catch (err) {
      setError(friendlyError(err.code));
    } finally { setLoading(false); }
  };

  const sendOtp = async () => {
    if (!phoneNum.trim()) { setError("សូមបញ្ចូលលេខទូរស័ព្ទ · Please enter your phone number"); return; }
    setError(""); setLoading(true);
    try {
      if (!recaptchaVerifierRef.current) {
        recaptchaVerifierRef.current = new firebase.auth.RecaptchaVerifier(
          recaptchaContainerRef.current,
          { size: "invisible" }
        );
        await recaptchaVerifierRef.current.render();
      }
      const result = await kAuth.signInWithPhoneNumber(phoneNum, recaptchaVerifierRef.current);
      setConfirmResult(result);
      setPhoneStep(2);
    } catch (err) {
      setError(friendlyError(err.code));
      recaptchaVerifierRef.current?.clear();
      recaptchaVerifierRef.current = null;
    } finally { setLoading(false); }
  };

  const verifyOtp = async () => {
    if (!otp.trim()) { setError("សូមបញ្ចូលលេខកូដ · Please enter the 6-digit code"); return; }
    setError(""); setLoading(true);
    try {
      await confirmResult.confirm(otp);
      // onAuthStateChanged in app.jsx handles the rest
    } catch (err) {
      setError(friendlyError(err.code));
    } finally { setLoading(false); }
  };

  const resendOtp = () => {
    recaptchaVerifierRef.current?.clear();
    recaptchaVerifierRef.current = null;
    setPhoneStep(1);
    setOtp("");
    setConfirmResult(null);
    setError("");
  };

  const headerTitle    = tab === "login" ? "ចូលគណនី។" : tab === "register" ? "បង្កើតគណនី។" : "ចូលដោយទូរស័ព្ទ។";
  const headerSubtitle = tab === "login" ? "Sign in to your account." : tab === "register" ? "Create your KSHOP24.NET account." : "Sign in with your phone number.";

  return (
    <main style={{ padding: "64px 0 96px" }}>
      <div className="wrap-narrow" style={{ maxWidth: 560 }}>

        {/* Header */}
        <div className="col gap-8" style={{ marginBottom: 36 }}>
          <span className="eyebrow">— <span className="km-sans">គណនី</span> · Account</span>
          <h1 className="display-lg km">{headerTitle}</h1>
          <span className="serif text-muted" style={{ fontSize: "var(--text-2xl)" }}>
            <em>{headerSubtitle}</em>
          </span>
        </div>

        {/* Tab bar */}
        <div role="tablist" aria-label="Sign in method" className="row" style={{ borderBottom: "1px solid var(--line)", marginBottom: 32 }}>
          {[["login", "ចូលគណនី", "Sign in"], ["register", "ចុះឈ្មោះ", "Register"], ["phone", "ទូរស័ព្ទ", "Phone"]].map(([id, kh, en]) => (
            <button
              key={id}
              type="button"
              role="tab"
              aria-selected={tab === id}
              onClick={() => setTab(id)}
              style={{
                background: "transparent", border: 0, cursor: "pointer",
                padding: "12px 20px", font: "inherit",
                color: tab === id ? "var(--fg)" : "var(--fg-muted)",
                borderBottom: "2px solid " + (tab === id ? "var(--accent)" : "transparent"),
                marginBottom: -1, display: "flex", flexDirection: "column", alignItems: "center", gap: 2
              }}
            >
              <span className="km-sans" style={{ fontSize: "var(--text-xs)" }}>{kh}</span>
              <span style={{ fontSize: "var(--text-2xs)", fontFamily: "var(--font-mono)", letterSpacing: "0.05em", opacity: 0.7 }}>{en}</span>
            </button>
          ))}
        </div>

        {/* ── Email/password forms ── */}
        {tab !== "phone" && (
          <form onSubmit={tab === "login" ? login : register}>
            <div className="col gap-16">
              {tab === "register" && (
                <Field label="ឈ្មោះ · Full name" value={form.name} onChange={set("name")} placeholder="Sophea Chan" required />
              )}
              <Field label="អ៊ីមែល · Email" type="email" value={form.email} onChange={set("email")} placeholder="you@example.com" required />
              {tab === "register" && (
                <Field label="លេខទូរស័ព្ទ · Phone (optional)" type="tel" value={form.phone} onChange={set("phone")} placeholder="+855 92 555 014" />
              )}
              <Field label="លេខសម្ងាត់ · Password" type="password" value={form.password} onChange={set("password")} placeholder="Min. 6 characters" required />
              {tab === "register" && (
                <Field label="បញ្ជាក់លេខសម្ងាត់ · Confirm password" type="password" value={form.confirm} onChange={set("confirm")} placeholder="Same password again" required />
              )}

              {error && <ErrorBox msg={error} />}

              <button type="submit" className="btn btn-primary btn-lg" style={{ width: "100%", marginTop: 4 }} disabled={loading}>
                {loading
                  ? <span className="km-sans">កំពុងដំណើរការ…</span>
                  : tab === "login"
                    ? <><span className="km-sans">ចូលគណនី</span> · Sign in <Icon name="arrow-right" size={16} /></>
                    : <><span className="km-sans">បង្កើតគណនី</span> · Create account <Icon name="arrow-right" size={16} /></>
                }
              </button>

              <Divider />

              <button type="button" className="btn" style={{ width: "100%", gap: 10, justifyContent: "center" }} onClick={googleSignIn} disabled={loading}>
                <GoogleMark />
                <span className="km-sans" style={{ fontSize: "var(--text-xs)" }}>ចូលដោយប្រើ Google</span>
                <span style={{ opacity: 0.6 }}>· Continue with Google</span>
              </button>
            </div>
          </form>
        )}

        {/* ── Phone OTP flow ── */}
        {tab === "phone" && (
          <div className="col gap-16">
            {phoneStep === 1 ? (
              <>
                <Field
                  label="លេខទូរស័ព្ទ · Phone number"
                  type="tel"
                  value={phoneNum}
                  onChange={e => setPhoneNum(e.target.value)}
                  placeholder="+855 92 555 014"
                />
                <span className="text-muted" style={{ fontSize: "var(--text-xs)", marginTop: -6 }}>
                  Include country code · +855 for Cambodia
                </span>

                {error && <ErrorBox msg={error} />}

                <button type="button" className="btn btn-primary btn-lg" style={{ width: "100%", marginTop: 4 }} onClick={sendOtp} disabled={loading}>
                  {loading
                    ? <span className="km-sans">កំពុងផ្ញើ…</span>
                    : <><span className="km-sans">ផ្ញើលេខកូដ</span> · Send OTP <Icon name="arrow-right" size={16} /></>
                  }
                </button>

                <Divider />

                <button type="button" className="btn" style={{ width: "100%", gap: 10, justifyContent: "center" }} onClick={googleSignIn} disabled={loading}>
                  <GoogleMark />
                  <span className="km-sans" style={{ fontSize: "var(--text-xs)" }}>ចូលដោយប្រើ Google</span>
                  <span style={{ opacity: 0.6 }}>· Continue with Google</span>
                </button>
              </>
            ) : (
              <>
                {/* Show which number we sent to */}
                <div style={{ padding: "12px 14px", background: "var(--bg-2)", borderRadius: "var(--radius)", border: "1px solid var(--line)" }}>
                  <span className="km-sans text-muted" style={{ fontSize: "var(--text-xs)" }}>បានផ្ញើទៅ · Sent to </span>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: "var(--text-xs)" }}>{phoneNum}</span>
                </div>

                <Field
                  label="លេខកូដផ្ទៀងផ្ទាត់ · Verification code"
                  type="tel"
                  value={otp}
                  onChange={e => setOtp(e.target.value.replace(/\D/g, "").slice(0, 6))}
                  placeholder="6-digit code"
                />

                {error && <ErrorBox msg={error} />}

                <button type="button" className="btn btn-primary btn-lg" style={{ width: "100%", marginTop: 4 }} onClick={verifyOtp} disabled={loading}>
                  {loading
                    ? <span className="km-sans">កំពុងផ្ទៀងផ្ទាត់…</span>
                    : <><span className="km-sans">ផ្ទៀងផ្ទាត់</span> · Verify <Icon name="check" size={16} /></>
                  }
                </button>

                <button type="button" onClick={resendOtp} style={{ background: "none", border: 0, cursor: "pointer", color: "var(--fg-muted)", fontSize: "var(--text-xs)", fontFamily: "inherit", padding: 0, textAlign: "center" }}>
                  <span className="km-sans">មិនទទួលបានលេខកូដ?</span> · Didn't receive a code? <span style={{ textDecoration: "underline" }}>Resend</span>
                </button>
              </>
            )}

            {/* Invisible reCAPTCHA container */}
            <div ref={recaptchaContainerRef} />
          </div>
        )}

      </div>
    </main>
  );
}

// Small shared sub-components used inside AuthScreen
function ErrorBox({ msg }) {
  return (
    <div style={{ padding: "10px 14px", background: "color-mix(in oklab, var(--accent) 12%, transparent)", borderRadius: "var(--radius)", border: "1px solid var(--accent)" }}>
      <span className="km-sans" style={{ color: "var(--accent)", fontSize: "var(--text-xs)" }}>{msg}</span>
    </div>
  );
}
function Divider() {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, color: "var(--fg-muted)" }}>
      <div style={{ flex: 1, height: 1, background: "var(--line-strong)" }} />
      <span style={{ fontFamily: "var(--font-mono)", fontSize: "var(--text-2xs)", letterSpacing: "0.08em" }}>OR</span>
      <div style={{ flex: 1, height: 1, background: "var(--line-strong)" }} />
    </div>
  );
}

// ─── Signed-in account page ────────────────────────────────────────────────

function AccountPage({ user, isAdmin }) {
  const [profile,     setProfile]     = useState(null);
  const [orders,      setOrders]      = useState([]);
  const [editing,     setEditing]     = useState(false);
  const [editForm,    setEditForm]    = useState({});
  const [saving,      setSaving]      = useState(false);
  const [loadingData, setLoadingData] = useState(true);

  useEffect(() => {
    if (!user) return;

    const unsubProfile = kDb
      .collection("users").doc(user.uid)
      .onSnapshot(doc => {
        if (!doc.exists) {
          // Auto-create profile for phone/Google sign-ins
          kDb.collection("users").doc(user.uid).set({
            name:        user.displayName || "",
            email:       user.email || "",
            phone:       user.phoneNumber || "",
            address:     "",
            memberSince: firebase.firestore.FieldValue.serverTimestamp()
          });
        }
        const data = doc.exists ? doc.data() : {};
        setProfile(data);
        setEditForm(data);
        setLoadingData(false);
      }, () => setLoadingData(false));

    const unsubOrders = kDb
      .collection("orders")
      .where("uid", "==", user.uid)
      .onSnapshot(
        snap => {
          const list = snap.docs.map(d => ({ id: d.id, ...d.data() }));
          list.sort((a, b) => (b.createdAt?.toMillis?.() || 0) - (a.createdAt?.toMillis?.() || 0));
          setOrders(list);
        },
        () => {}
      );

    return () => { unsubProfile(); unsubOrders(); };
  }, [user]);

  const saveProfile = async e => {
    e.preventDefault();
    setSaving(true);
    try {
      await kDb.collection("users").doc(user.uid).set({
        name:    editForm.name    || "",
        phone:   editForm.phone   || "",
        address: editForm.address || "",
        email:   user.email,
        memberSince: profile?.memberSince || firebase.firestore.FieldValue.serverTimestamp()
      }, { merge: true });
      if (editForm.name) await user.updateProfile({ displayName: editForm.name });
      setEditing(false);
    } finally { setSaving(false); }
  };

  const signOut = () => kAuth.signOut();

  if (loadingData) return <LoadingSpinner />;

  const displayName = profile?.name || user.displayName || user.email?.split("@")[0] || "អ្នកប្រើ";
  const firstName   = displayName.split(" ")[0];
  const memberDate  = profile?.memberSince?.toDate?.();
  const memberStr   = memberDate
    ? memberDate.toLocaleDateString("en-US", { month: "short", year: "numeric" }).toUpperCase()
    : "—";

  return (
    <main style={{ padding: "48px 0 96px" }}>
      <div className="wrap">

        {/* Page header */}
        <div className="row justify-between items-end flex-wrap gap-16" style={{ marginBottom: 48 }}>
          <div className="col gap-8">
            <span className="eyebrow">— <span className="km-sans">គណនី</span> · Account</span>
            <h1 className="display-lg km">សូមស្វាគមន៍{firstName ? ", " + firstName : ""}។</h1>
            <span className="serif text-muted" style={{ fontSize: "var(--text-2xl)" }}>
              <em>Welcome back{firstName ? ", " + firstName : ""}.</em>
            </span>
          </div>
          <div className="col gap-10 items-end">
            <span className="mono text-muted" style={{ fontSize: "var(--text-2xs)", letterSpacing: "0.08em" }}>
              <span className="km-sans" style={{ letterSpacing: 0 }}>សមាជិក</span> · MEMBER SINCE {memberStr}
            </span>
            <button type="button" className="btn" onClick={signOut} style={{ fontSize: "var(--text-2xs)" }}>
              <span className="km-sans">ចាកចេញ</span> · Sign out
            </button>
          </div>
        </div>

        {/* Two-column layout: profile left, orders right */}
        <div className="split-science" style={{ alignItems: "start" }}>

          {/* ── Profile card ── */}
          <div style={{ border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden" }}>
            <div className="row justify-between items-center" style={{ padding: "14px 20px", borderBottom: "1px solid var(--line)", background: "var(--bg-2)" }}>
              <span className="mono" style={{ fontSize: "var(--text-2xs)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
                <span className="km-sans" style={{ textTransform: "none", letterSpacing: 0 }}>ព័ត៌មានផ្ទាល់ខ្លួន</span> · Profile
              </span>
              {!editing && (
                <button type="button" className="btn btn-ghost" style={{ fontSize: "var(--text-2xs)", padding: "4px 10px" }} onClick={() => setEditing(true)}>
                  <span className="km-sans">កែប្រែ</span> · Edit
                </button>
              )}
            </div>

            {editing ? (
              <form onSubmit={saveProfile} style={{ padding: 20 }}>
                <div className="col gap-14">
                  <Field label="ឈ្មោះ · Full name"          value={editForm.name    || ""} onChange={e => setEditForm(p => ({ ...p, name:    e.target.value }))} placeholder="Sophea Chan" />
                  <Field label="អ៊ីមែល · Email"             value={user.email       || ""} disabled />
                  <Field label="លេខទូរស័ព្ទ · Phone"         value={editForm.phone   || ""} onChange={e => setEditForm(p => ({ ...p, phone:   e.target.value }))} placeholder="+855 92 555 014" type="tel" />
                  <Field label="អាសយដ្ឋាន · Delivery address" value={editForm.address || ""} onChange={e => setEditForm(p => ({ ...p, address: e.target.value }))} placeholder="St. 271, Toul Tompoung, Phnom Penh" />
                  <div className="row gap-8" style={{ marginTop: 4 }}>
                    <button type="submit" className="btn btn-primary" disabled={saving}>
                      {saving ? <span className="km-sans">កំពុងរក្សាទុក…</span> : <><span className="km-sans">រក្សាទុក</span> · Save</>}
                    </button>
                    <button type="button" className="btn" onClick={() => { setEditing(false); setEditForm(profile); }}>
                      <span className="km-sans">បោះបង់</span> · Cancel
                    </button>
                  </div>
                </div>
              </form>
            ) : (
              <div className="col">
                {[
                  ["ឈ្មោះ",    "Name",    profile?.name    || "—"],
                  ["អ៊ីមែល",  "Email",   user.email       || "—"],
                  ["ទូរស័ព្ទ",  "Phone",   profile?.phone   || "—"],
                  ["អាសយដ្ឋាន","Address", profile?.address || "—"],
                ].map(([kh, en, val], i, arr) => (
                  <div key={en} style={{
                    display: "grid", gridTemplateColumns: "130px 1fr",
                    padding: "14px 20px",
                    borderBottom: i < arr.length - 1 ? "1px solid var(--line)" : "none",
                    alignItems: "start"
                  }}>
                    <div className="col gap-1">
                      <span className="km-sans" style={{ fontSize: "var(--text-xs)" }}>{kh}</span>
                      <span className="mono text-muted" style={{ fontSize: "var(--text-2xs)", letterSpacing: "0.06em" }}>{en.toUpperCase()}</span>
                    </div>
                    <span style={{ fontSize: "var(--text-sm)", paddingTop: 2, wordBreak: "break-word" }}>{val}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* ── Order history ── */}
          <div className="col gap-0">
            <div className="row justify-between items-center" style={{ padding: "16px 0", borderTop: "1px solid var(--line-strong)", borderBottom: "1px solid var(--line)" }}>
              <span className="mono" style={{ fontSize: "var(--text-2xs)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
                <span className="km-sans" style={{ letterSpacing: 0, textTransform: "none" }}>ប្រវត្តិការបញ្ជាទិញ</span> · Order history
              </span>
              <span className="mono text-muted" style={{ fontSize: "var(--text-2xs)" }}>{orders.length} ORDERS</span>
            </div>

            {orders.length === 0 ? (
              <div className="col gap-10 items-center" style={{ padding: "56px 0", textAlign: "center" }}>
                <div style={{ width: 48, height: 48, borderRadius: 999, border: "1px solid var(--line-strong)", display: "grid", placeItems: "center", color: "var(--fg-muted)" }}>
                  <Icon name="cart" size={22} />
                </div>
                <div className="col gap-4 items-center">
                  <span className="km-sans text-muted" style={{ fontSize: "var(--text-base)" }}>មិនទាន់មានការបញ្ជាទិញ</span>
                  <span className="text-muted" style={{ fontSize: "var(--text-sm)" }}>No orders yet.</span>
                </div>
              </div>
            ) : (
              <div className="admin-table-scroll"><div className="admin-table-inner" style={{ minWidth: 560 }}>
              {orders.map(o => {
                const date = o.createdAt?.toDate?.().toLocaleDateString("en-US", { day: "numeric", month: "short", year: "numeric" }) || "—";
                const statusColor = o.status === "delivered" ? "var(--primary)" : o.status === "shipped" ? "#7c3aed" : o.status === "confirmed" ? "#2563eb" : o.status === "pending_payment" ? "#f59e0b" : "var(--accent)";
                const statusLabel = { pending: "PENDING", pending_payment: "AWAITING PAYMENT", confirmed: "CONFIRMED", shipped: "SHIPPED", delivered: "DELIVERED" }[o.status] || (o.status || "pending").toUpperCase();
                return (
                  <div key={o.id} style={{
                    display: "grid", gridTemplateColumns: isAdmin ? "1.2fr 1fr 1fr 2fr 0.8fr auto" : "1.2fr 1fr 1fr 2fr 0.8fr",
                    gap: 16, padding: "20px 0",
                    borderBottom: "1px solid var(--line)", alignItems: "center"
                  }}>
                    <span className="mono" style={{ fontSize: "var(--text-xs)" }}>KS-{o.id.slice(0, 8).toUpperCase()}</span>
                    <span className="text-muted" style={{ fontSize: "var(--text-2xs)" }}>{date}</span>
                    <span className="chip mono" style={{ fontSize: "var(--text-2xs)", padding: "3px 8px", alignSelf: "start", color: statusColor, borderColor: statusColor }}>
                      {statusLabel}
                    </span>
                    <div className="col gap-2">
                      {(o.items || []).map((it, j) => (
                        <span key={j} className="km-sans" style={{ fontSize: "var(--text-xs)" }}>{it.labelKh || it.label} ×{it.qty}</span>
                      ))}
                    </div>
                    <span className="serif" style={{ fontSize: "var(--text-xl)" }}>${Number(o.total || 0).toFixed(2)}</span>
                    {isAdmin && (
                      <button
                        type="button"
                        className="btn"
                        style={{ fontSize: "var(--text-2xs)", padding: "5px 10px", whiteSpace: "nowrap" }}
                        onClick={() => printSlipWithQR(o)}
                      >
                        <Icon name="printer" size={12} />
                        Print
                      </button>
                    )}
                  </div>
                );
              })}
              </div></div>
            )}
          </div>
        </div>
      </div>
    </main>
  );
}

// ─── Root — switches between loading / auth / account ─────────────────────

function AccountRoot({ user, authLoading, isAdmin }) {
  if (authLoading) return <LoadingSpinner />;
  if (!user)       return <AuthScreen />;
  return <AccountPage user={user} isAdmin={isAdmin} />;
}

Object.assign(window, { AccountRoot });
