// Checkout — address + payment flow (replaces Instagram DM)

const AIMAGS = [
  "Улаанбаатар",
  "Архангай","Баян-Өлгий","Баянхонгор","Булган","Говь-Алтай","Говьсүмбэр",
  "Дархан-Уул","Дорноговь","Дорнод","Дундговь","Завхан","Орхон",
  "Өвөрхангай","Өмнөговь","Сүхбаатар","Сэлэнгэ","Төв","Увс","Ховд","Хөвсгөл","Хэнтий",
];
const UB_DUUREGS = [
  "Баянгол дүүрэг","Баянзүрх дүүрэг","Чингэлтэй дүүрэг","Сүхбаатар дүүрэг",
  "Хан-Уул дүүрэг","Сонгинохайрхан дүүрэг","Налайх дүүрэг","Багануур дүүрэг","Багахангай дүүрэг",
];

function DMOrder({ items, onBack, couponDiscount }) {
  const mob = typeof window !== "undefined" && window.innerWidth < 768;
  const subtotal  = items.reduce((s, i) => s + i.price * i.qty, 0);
  const discount  = couponDiscount || 0;
  const total     = subtotal - Math.round(subtotal * discount / 100);

  const [pay,  setPay]  = React.useState("cash");   // cash | bank
  const [step, setStep] = React.useState(1);         // 1=address 2=success

  const [aimagIdx, setAimagIdx] = React.useState(0);
  const [duureg,   setDuureg]   = React.useState("");
  const [horoo,    setHoroo]    = React.useState("");
  const [bair,     setBair]     = React.useState("");
  const [davhar,   setDavhar]   = React.useState("");
  const [toot,     setToot]     = React.useState("");
  const [extra,    setExtra]    = React.useState("");
  const [name,     setName]     = React.useState("");
  const [phone,    setPhone]    = React.useState("");
  const [errors,   setErrors]   = React.useState({});

  const isUB = AIMAGS[aimagIdx] === "Улаанбаатар";

  const validate = () => {
    const e = {};
    if (!name.trim())   e.name   = true;
    if (!phone.trim())  e.phone  = true;
    if (isUB && !duureg)  e.duureg = true;
    if (!horoo.trim())  e.horoo  = true;
    if (!bair.trim())   e.bair   = true;
    if (!davhar.trim()) e.davhar = true;
    if (!toot.trim())   e.toot   = true;
    return e;
  };

  const submit = () => {
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length > 0) return;

    const address = AIMAGS[aimagIdx] + (duureg ? ", " + duureg : "") + ", " + horoo + "-р хороо, " + bair + " байр, " + davhar + "-р давхар, " + toot + " тоот";

    const newOrder = {
      id: "ORD-" + Date.now(),
      date: new Date().toISOString().slice(0, 10),
      customer: name,
      phone: phone,
      address: address,
      products: items.map(it => it.name + " x" + it.qty).join(", "),
      items: items,
      total: total,
      payment: pay,
      status: "pending",
      coupon: discount > 0 ? "-" + discount + "%" : null,
    };

    fetch("/api/save-order", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(newOrder),
    }).catch(() => {});

    setStep(2);
  };

  const inp = (err) => ({
    border: err ? "1.5px solid #FF3B6F" : "1px solid #E8E7E9",
    borderRadius: 12, padding: "11px 14px",
    fontFamily: "Inter, sans-serif", fontSize: 14, color: "#0E0D11",
    background: "#fff", outline: "none", width: "100%", boxSizing: "border-box",
  });

  const lbl = { fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "#8A8990", display: "block", marginBottom: 7 };
  const frow = { marginBottom: 16 };
  const errMsg = { fontFamily: "Inter", fontSize: 12, color: "#FF3B6F", marginTop: 5 };

  if (step === 2) return (
    <section style={{ maxWidth: 480, margin: "0 auto", padding: mob ? "32px 20px 60px" : "80px 24px", textAlign: "center" }}>
      <div style={{ fontSize: 44, marginBottom: 12 }}>✦</div>
      <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "#8A8990" }}>ЗАХИАЛГА БАТАЛГААЖЛАА</span>
      <h1 style={{ fontFamily: "Inter", fontWeight: 900, fontSize: mob ? 36 : 52, letterSpacing: "-0.035em", textTransform: "uppercase", color: "#0E0D11", margin: "10px 0 18px", lineHeight: 1.0 }}>
        ЗАХИАЛГА<br/>БАТАЛГААЖЛАА
      </h1>
      <p style={{ fontFamily: "Caveat, cursive", fontSize: mob ? 22 : 26, color: "#0E0D11", lineHeight: 1.5, margin: "0 0 8px", fontWeight: 600 }}>
        Таны захиалга 1–2 хоногт очно.
      </p>
      <p style={{ fontFamily: "Caveat, cursive", fontSize: mob ? 19 : 22, color: "#4A4852", lineHeight: 1.5, margin: "0 0 24px" }}>
        Асуух зүйл байвал Instagram-аар{" "}
        <a href="https://instagram.com/nine.ub9" target="_blank" style={{ color: "#FF3B6F", textDecoration: "none", fontWeight: 700 }}>@nine.ub9</a>{" "}
        бичээрэй.
      </p>
      <div style={{ display: "flex", flexDirection: mob ? "column" : "row", alignItems: "center", justifyContent: "center", gap: mob ? 10 : 24, margin: "0 0 24px", padding: mob ? "16px 20px" : "18px 28px", background: "#0E0D11", borderRadius: 16 }}>
        <a href="tel:55161160" style={{ fontFamily: "Caveat, cursive", fontSize: mob ? 20 : 22, fontWeight: 700, color: "#FFEC42", textDecoration: "none", letterSpacing: "0.02em", display:"flex", alignItems:"center", gap:8 }}>
          📞 55-16-11-60
        </a>
        {mob && <div style={{ width: "100%", height: 1, background: "rgba(255,255,255,0.1)" }} />}
        <a href="mailto:n9ne.ub@gmail.com" style={{ fontFamily: "Caveat, cursive", fontSize: mob ? 18 : 22, fontWeight: 700, color: "#FF3B6F", textDecoration: "none", letterSpacing: "0.02em", display:"flex", alignItems:"center", gap:8, wordBreak:"break-all" }}>
          ✉ n9ne.ub@gmail.com
        </a>
      </div>
      <button onClick={onBack} style={{ width: mob ? "100%" : "auto", background: "#1F1D23", color: "#fff", border: "none", borderRadius: 12, padding: "15px 28px", fontFamily: "Inter", fontWeight: 600, fontSize: 14, cursor: "pointer" }}>
        ← Дэлгүүр рүү буцах
      </button>
    </section>
  );

  return (
    <section style={{ ...co.wrap, padding: mob ? "16px 16px 60px" : "24px 24px 80px" }}>
      <a onClick={onBack} style={co.back}>← Буцах</a>
      <div style={{ ...co.grid, gridTemplateColumns: mob ? "1fr" : "1.3fr 1fr", gap: mob ? 16 : 48 }}>

        {/* ─── Mobile: summary first ─── */}
        {mob && (
          <aside style={{ ...co.summary, position:"static" }}>
            <span style={co.meta}>ТАНЫ ЗАХИАЛГА</span>
            <h3 style={{ margin:"6px 0 16px", fontFamily:"Inter", fontWeight:900, fontSize:18, letterSpacing:"-0.02em", textTransform:"uppercase", color:"#0E0D11" }}>
              {items.reduce((s,i) => s+i.qty, 0)} БАРАА
            </h3>
            <div style={{ display:"flex", flexDirection:"column" }}>
              {items.map((it,i) => (
                <div key={i} style={{ display:"flex", gap:12, alignItems:"center", padding:"10px 0", borderBottom:"1px solid #F2F1F3" }}>
                  <div style={{ width:48, height:48, borderRadius:10, background: it.img ? "#FAFAFB" : it.palette[0], display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0, overflow:"hidden" }}>
                    {it.img ? <img src={it.img} style={{ width:"100%", height:"100%", objectFit:"cover" }}/> : <img src="assets/chrome-orb.svg" style={{ width:"60%", height:"60%" }}/>}
                  </div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontFamily:"Inter", fontWeight:600, fontSize:13, color:"#0E0D11" }}>{it.name}</div>
                    <div style={{ fontFamily:"JetBrains Mono, monospace", fontSize:10, letterSpacing:"0.15em", textTransform:"uppercase", color:"#8A8990" }}>{it.color} × {it.qty}</div>
                  </div>
                  <span style={{ fontFamily:"Inter", fontWeight:700, fontSize:14, color:"#0E0D11" }}>₮{(it.price*it.qty).toLocaleString()}</span>
                </div>
              ))}
            </div>
            <div style={{ display:"flex", flexDirection:"column", gap:8, padding:"14px 0 4px" }}>
              <div style={{ display:"flex", justifyContent:"space-between", fontFamily:"Inter", fontSize:14, color:"#0E0D11" }}>
                <span>Нийт дүн</span><span>₮{subtotal.toLocaleString()}</span>
              </div>
              {discount > 0 && (
                <div style={{ display:"flex", justifyContent:"space-between", fontFamily:"Inter", fontSize:14, color:"#FF6A30" }}>
                  <span>Купон -{discount}%</span><span>-₮{Math.round(subtotal*discount/100).toLocaleString()}</span>
                </div>
              )}
              <div style={{ display:"flex", justifyContent:"space-between", fontFamily:"Inter", fontSize:14, color:"#0E0D11" }}>
                <span>Хүргэлт</span><span style={{ color:"#16A34A", fontWeight:600 }}>Үнэгүй</span>
              </div>
              <div style={{ display:"flex", justifyContent:"space-between", marginTop:8, paddingTop:12, borderTop:"1px solid #E8E7E9", fontFamily:"Inter", fontWeight:900, fontSize:18, letterSpacing:"-0.02em", textTransform:"uppercase", color:"#0E0D11" }}>
                <span>НИЙТ</span><span>₮{total.toLocaleString()}</span>
              </div>
            </div>
          </aside>
        )}

        {/* ─── LEFT: form ─── */}
        <div>
          <span style={co.meta}>/ ЗАХИАЛГА БҮРТГЭЛ /</span>
          <h1 style={{ ...co.title, fontSize: mob ? 40 : 64, margin: mob ? "6px 0 16px" : "8px 0 20px" }}>Хаяг &amp;<br/>Төлбөр</h1>

          {/* Error summary */}
          {Object.keys(errors).length > 0 && (
            <div style={{ background: "#FF3B6F11", border: "1.5px solid #FF3B6F44", borderRadius: 12, padding: "14px 18px", marginBottom: 24, fontFamily: "Inter", fontSize: 14, color: "#FF3B6F" }}>
              Захиалга өгхийг хүсвэл та хаягаа бүрэн бичнэ үү.
            </div>
          )}

          {/* Contact */}
          <div style={{ background: "#FAFAFB", border: "1px solid #E8E7E9", borderRadius: 16, padding: "20px 20px 4px", marginBottom: 20 }}>
            <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "#8A8990", marginBottom: 16 }}>Холбоо барих</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <div style={frow}>
                <label style={lbl}>Нэр *</label>
                <input style={inp(errors.name)} value={name} onChange={e => setName(e.target.value)} placeholder="Таны нэр" />
                {errors.name && <div style={errMsg}>Нэрээ бичнэ үү</div>}
              </div>
              <div style={frow}>
                <label style={lbl}>Утасны дугаар *</label>
                <input style={inp(errors.phone)} value={phone} onChange={e => setPhone(e.target.value)} placeholder="9900-0000" />
                {errors.phone && <div style={errMsg}>Утасны дугаараа бичнэ үү</div>}
              </div>
            </div>
          </div>

          {/* Address */}
          <div style={{ background: "#FAFAFB", border: "1px solid #E8E7E9", borderRadius: 16, padding: "20px 20px 4px", marginBottom: 20 }}>
            <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "#8A8990", marginBottom: 16 }}>Хүргэлтийн хаяг</div>

            {/* Орон нутаг */}
            <div style={frow}>
              <label style={lbl}>Орон нутаг *</label>
              <select
                style={{ ...inp(false), appearance:"none", WebkitAppearance:"none", fontSize:15, padding:"13px 14px", background:"#fff" }}
                value={AIMAGS[aimagIdx]}
                onChange={e => { setAimagIdx(AIMAGS.indexOf(e.target.value)); setDuureg(""); }}
              >
                {AIMAGS.map(a => <option key={a} value={a}>{a}</option>)}
              </select>
            </div>

            {/* Дүүрэг (UB only) */}
            {isUB && (
              <div style={frow}>
                <label style={lbl}>Дүүрэг *</label>
                <select style={{ ...inp(errors.duureg), appearance: "none" }} value={duureg} onChange={e => setDuureg(e.target.value)}>
                  <option value="">— Дүүрэг сонгох —</option>
                  {UB_DUUREGS.map(d => <option key={d} value={d}>{d}</option>)}
                </select>
                {errors.duureg && <div style={errMsg}>Дүүрэгээ сонгоно уу</div>}
              </div>
            )}

            {/* Хороо */}
            <div style={frow}>
              <label style={lbl}>{isUB ? "Хороо *" : "Сум/Баг *"}</label>
              <input style={inp(errors.horoo)} value={horoo} onChange={e => setHoroo(e.target.value)} placeholder={isUB ? "1-р хороо" : "Сум, баг"} />
              {errors.horoo && <div style={errMsg}>Хороог бичнэ үү</div>}
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
              <div style={frow}>
                <label style={lbl}>Байр *</label>
                <input style={inp(errors.bair)} value={bair} onChange={e => setBair(e.target.value)} placeholder="Байр/Гудамж" />
                {errors.bair && <div style={errMsg}>Бичнэ үү</div>}
              </div>
              <div style={frow}>
                <label style={lbl}>Давхар *</label>
                <input style={inp(errors.davhar)} value={davhar} onChange={e => setDavhar(e.target.value)} placeholder="3" />
                {errors.davhar && <div style={errMsg}>Бичнэ үү</div>}
              </div>
              <div style={frow}>
                <label style={lbl}>Тоот *</label>
                <input style={inp(errors.toot)} value={toot} onChange={e => setToot(e.target.value)} placeholder="42" />
                {errors.toot && <div style={errMsg}>Бичнэ үү</div>}
              </div>
            </div>

            <div style={frow}>
              <label style={lbl}>Нэмэлт мэдээлэл</label>
              <textarea
                style={{ ...inp(false), height: 72, resize: "vertical" }}
                value={extra}
                onChange={e => setExtra(e.target.value)}
                placeholder="Хаяг олоход хялбар болгох нэмэлт мэдээлэл..."
              />
            </div>
          </div>

          {/* Payment */}
          <div style={{ background: "#FAFAFB", border: "1px solid #E8E7E9", borderRadius: 16, padding: "20px", marginBottom: 24 }}>
            <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "#8A8990", marginBottom: 16 }}>Төлбөрийн хэлбэр</div>
            <div style={{ display: "flex", gap: 12 }}>
              {[
                { id: "cash", label: "💵 Бэлнээр", desc: "Хүргэлтийн үед төлнө" },
                { id: "bank", label: "🏦 Дансаар", desc: "M Bank · 8734122395" },
              ].map(p => (
                <button key={p.id} onClick={() => setPay(p.id)} style={{
                  flex: 1, padding: "16px", borderRadius: 14, textAlign: "left", cursor: "pointer",
                  border: pay === p.id ? "2px solid #0E0D11" : "1px solid #E8E7E9",
                  background: pay === p.id ? "#0E0D11" : "#fff",
                }}>
                  <div style={{ fontFamily: "Inter", fontWeight: 600, fontSize: 15, color: pay === p.id ? "#fff" : "#0E0D11" }}>{p.label}</div>
                  <div style={{ fontFamily: "Inter", fontSize: 12, color: pay === p.id ? "rgba(255,255,255,0.6)" : "#8A8990", marginTop: 4 }}>{p.desc}</div>
                </button>
              ))}
            </div>
            {pay === "cash" && (
              <div style={{ marginTop: 14, padding: "14px 16px", background: "#FF3B6F15", border: "1.5px solid #FF3B6F", borderRadius: 10 }}>
                <div style={{ fontFamily: "Inter", fontWeight: 700, fontSize: 13, color: "#FF3B6F", lineHeight: 1.5 }}>
                  ⚠️ Орон нутагт унаанд тавих бол заавал төлбөрөө бүрэн төлнө үү!
                </div>
              </div>
            )}
            {pay === "bank" && (
              <div style={{ marginTop: 14, padding: "16px", background: "#FFEC4215", border: "1px solid #FFEC4240", borderRadius: 10 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                  <img src="assets/mbank-logo.svg" style={{ width: 32, height: 32, borderRadius: 7, flexShrink: 0 }} />
                  <div style={{ fontFamily: "Inter", fontWeight: 900, fontSize: 16, color: "#0E0D11", letterSpacing: "-0.01em" }}>M Bank</div>
                </div>
                <div style={{ fontFamily: "Inter", fontWeight: 700, fontSize: 18, color: "#0E0D11" }}>MN68003900 · 8734122395</div>
                <div style={{ fontFamily: "Inter", fontSize: 13, color: "#4A4852", marginTop: 2 }}>Хүлээн авагч: MUNKHJARGAL</div>
                <div style={{ fontFamily: "Inter", fontSize: 13, color: "#4A4852", marginTop: 2 }}>Гүйлгээний утга: Таны нэр + утасны дугаар</div>
              </div>
            )}
          </div>

          <button onClick={submit} style={{ width: "100%", background: "#1F1D23", color: "#fff", border: "none", borderRadius: 14, padding: "18px", fontFamily: "Inter", fontWeight: 700, fontSize: 15, cursor: "pointer", letterSpacing: "-0.01em" }}>
            Захиалга баталгаажуулах ✦
          </button>
        </div>

        {/* ─── RIGHT: order summary (desktop only) ─── */}
        {!mob && <aside style={co.summary}>
          <span style={co.meta}>ТАНЫ ЗАХИАЛГА</span>
          <h3 style={{ margin: "6px 0 16px", fontFamily: "Inter", fontWeight: 900, fontSize: 20, letterSpacing: "-0.02em", textTransform: "uppercase", color: "#0E0D11" }}>
            {items.reduce((s, i) => s + i.qty, 0)} БАРАА
          </h3>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {items.map((it, i) => (
              <div key={i} style={{ display: "flex", gap: 12, alignItems: "center", padding: "12px 0", borderBottom: "1px solid #F2F1F3" }}>
                <div style={{ width: 54, height: 54, borderRadius: 10, background: it.img ? "#FAFAFB" : it.palette[0], display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, overflow: "hidden" }}>
                  {it.img
                    ? <img src={it.img} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                    : <img src="assets/chrome-orb.svg" style={{ width: "60%", height: "60%" }} />
                  }
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "Inter", fontWeight: 600, fontSize: 14, color: "#0E0D11" }}>{it.name}</div>
                  <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "#8A8990" }}>{it.color} × {it.qty}</div>
                </div>
                <span style={{ fontFamily: "Inter", fontWeight: 700, fontSize: 14, color: "#0E0D11" }}>₮{(it.price * it.qty).toLocaleString()}</span>
              </div>
            ))}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, padding: "16px 0 4px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "Inter", fontSize: 14, color: "#0E0D11" }}>
              <span>Нийт дүн</span><span>₮{subtotal.toLocaleString()}</span>
            </div>
            {discount > 0 && (
              <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "Inter", fontSize: 14, color: "#FF6A30" }}>
                <span>Купон хямдрал -{discount}%</span><span>-₮{Math.round(subtotal * discount / 100).toLocaleString()}</span>
              </div>
            )}
            <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "Inter", fontSize: 14, color: "#0E0D11" }}>
              <span>Хүргэлт</span><span style={{ color: "#16A34A", fontWeight: 600 }}>Үнэгүй</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, paddingTop: 14, borderTop: "1px solid #E8E7E9", fontFamily: "Inter", fontWeight: 900, fontSize: 20, letterSpacing: "-0.02em", textTransform: "uppercase", color: "#0E0D11" }}>
              <span>НИЙТ</span><span>₮{total.toLocaleString()}</span>
            </div>
          </div>
        </aside>}
      </div>
    </section>
  );
}

const co = {
  wrap: { maxWidth: 1280, margin: "0 auto", padding: "24px 24px 80px" },
  back: { fontFamily: "JetBrains Mono, monospace", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "#0E0D11", cursor: "pointer", textDecoration: "none" },
  grid: { display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 48, marginTop: 24 },
  meta: { fontFamily: "JetBrains Mono, monospace", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "#8A8990" },
  title: { margin: "8px 0 20px", fontFamily: "Inter, sans-serif", fontWeight: 900, fontSize: 64, lineHeight: 0.95, letterSpacing: "-0.035em", textTransform: "uppercase", color: "#0E0D11" },
  summary: { background: "#FAFAFB", border: "1px solid #E8E7E9", borderRadius: 18, padding: "22px 24px", height: "max-content", position: "sticky", top: 80 },
};

window.DMOrder = DMOrder;
