/* Submit / checkout flow + confirmation — mode aware. Persists orders to localStorage. */
const { useState: useStateK, useEffect: useEffectK } = React;
const { PS_DATA: DK } = window;

/* Review sheet: shown before final submit/checkout */
function ReviewSheet({ design, entry, onConfirm, onClose }) {
  const etsy = entry.mode === "etsy";
  const size = DK.SIZES.find(s => s.id === design.size);
  const frame = DK.FRAMES.find(f => f.id === design.frame);
  const price = DK.priceFor(design);
  const photoMissing = (DK.TEMPLATES.find(t => t.id === design.templateId) || {}).kind === "photo" && !design.photo;

  useEffectK(() => {
    const onKey = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const rows = [
    ["LayoutTemplate", "Design", (DK.TEMPLATES.find(t => t.id === design.templateId) || {}).name],
    ["Ruler", "Size", size.label + " cm · " + size.sub],
    ["Frame", "Frame", frame.label + (frame.add ? ` (+$${frame.add})` : "")],
  ];

  return (
    <div onClick={onClose} style={{ position: "absolute", inset: 0, zIndex: 40, display: "flex", alignItems: "center", justifyContent: "center", padding: 16, background: "rgba(40,28,16,.46)", backdropFilter: "blur(3px)", animation: "fadeIn .2s" }}>
      <div onClick={e => e.stopPropagation()} role="dialog" aria-modal="true" style={{ width: "min(460px,100%)", maxHeight: "95%", overflowY: "auto", background: "var(--card)", borderRadius: "var(--r-xl)", boxShadow: "var(--sh-lg)", border: "1px solid var(--line)", animation: "riseIn .26s var(--ease-out)" }} className="scroll-y">
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 22px 14px", borderBottom: "1px solid var(--line)" }}>
          <span style={{ fontFamily: "var(--serif)", fontSize: 20, fontWeight: 600 }}>{etsy ? "Submit your design" : "Add to cart"}</span>
          <button className="btn-icon btn-ghost" style={{ width: 34, height: 34, minHeight: 34 }} onClick={onClose}><Icon name="X" size={17} /></button>
        </div>

        <div style={{ padding: "20px 22px" }}>
          <div style={{ display: "flex", gap: 16, alignItems: "center", marginBottom: 18 }}>
            <div style={{ flex: "none" }}><Poster d={design} maxH={150} maxW={150 * size.ratio} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: "var(--serif)", fontSize: 18, fontWeight: 600, color: "var(--ink)" }}>{entry.productName}</div>
              <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 3 }}>{size.label} cm · {frame.label}</div>
              {etsy && <div style={{ display: "inline-flex", alignItems: "center", gap: 6, marginTop: 9, padding: "4px 10px", borderRadius: 99, background: "var(--sage-tint)", color: "#46522F", fontSize: 11.5, fontWeight: 700 }}><Icon name="BadgeCheck" size={13} /> Paid · {entry.orderRef}</div>}
            </div>
          </div>

          {photoMissing && (
            <div style={{ display: "flex", gap: 9, alignItems: "center", padding: "11px 13px", background: "#F6E2D2", border: "1px solid #E7C2A6", borderRadius: "var(--r-md)", color: "#8F4124", marginBottom: 16, fontSize: 13, fontWeight: 600 }}>
              <Icon name="TriangleAlert" size={16} /> This template has an empty photo slot — add a photo first.
            </div>
          )}

          <div style={{ display: "flex", flexDirection: "column", gap: 0, marginBottom: etsy ? 4 : 14 }}>
            {rows.map(([ic, k, v], i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 2px", borderBottom: i < rows.length - 1 ? "1px solid var(--line)" : "none" }}>
                <Icon name={ic} size={16} style={{ color: "var(--clay)" }} />
                <span style={{ fontSize: 12.5, color: "var(--ink-3)", fontWeight: 600, width: 70, flex: "none" }}>{k}</span>
                <span style={{ fontSize: 14, color: "var(--ink)", fontWeight: 600 }}>{v}</span>
              </div>
            ))}
          </div>

          {!etsy && (
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", padding: "14px 2px 4px", borderTop: "2px solid var(--line)" }}>
              <span style={{ fontSize: 14, fontWeight: 700, color: "var(--ink)" }}>Total</span>
              <span style={{ fontFamily: "var(--serif)", fontSize: 26, fontWeight: 600, color: "var(--ink)" }}>${price}</span>
            </div>
          )}
          {etsy && (
            <p style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5, margin: "14px 0 0" }}>
              Once you submit, we'll prepare a digital proof and email it to you within 24 hours before printing. You can reply with changes.
            </p>
          )}
        </div>

        <div style={{ display: "flex", gap: 10, padding: "0 22px 22px" }}>
          <button className="btn btn-ghost" style={{ flex: "none" }} onClick={onClose}>Keep editing</button>
          <button className="btn btn-primary" style={{ flex: 1 }} disabled={photoMissing} onClick={() => !photoMissing && onConfirm()}>
            {etsy ? <><Icon name="Send" size={17} /> Submit my design</> : <><Icon name="ShoppingBag" size={17} /> Place order · ${price}</>}
          </button>
        </div>
      </div>
    </div>
  );
}

/* Confirmation screen after submit */
function DoneScreen({ order, entry, onRestart }) {
  const etsy = entry.mode === "etsy";
  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 45, display: "flex", alignItems: "center", justifyContent: "center", padding: 18, background: "rgba(240,231,214,.92)", backdropFilter: "blur(4px)", animation: "fadeIn .25s" }}>
      <div style={{ width: "min(440px,100%)", textAlign: "center", background: "var(--card)", borderRadius: "var(--r-xl)", boxShadow: "var(--sh-lg)", border: "1px solid var(--line)", padding: "34px 28px 28px", animation: "riseIn .3s var(--ease-out)" }}>
        <div style={{ width: 60, height: 60, borderRadius: "50%", background: "var(--sage-tint)", color: "#4A5436", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 18px" }}>
          <Icon name="Check" size={32} stroke={2.4} />
        </div>
        <h2 style={{ fontFamily: "var(--serif)", fontSize: 27, fontWeight: 600, margin: "0 0 8px" }}>{etsy ? "Design received!" : "Order placed!"}</h2>
        <p style={{ color: "var(--ink-2)", fontSize: 14.5, margin: "0 0 20px", lineHeight: 1.5 }}>
          {etsy
            ? "Thanks — we've got your personalization. A proof is on its way to your inbox within 24 hours."
            : "Thanks for your order! A confirmation and tracking link are on the way to your inbox."}
        </p>
        <div style={{ display: "flex", flexDirection: "column", gap: 9, padding: "15px 18px", background: "var(--paper-2)", borderRadius: "var(--r-md)", marginBottom: 22, textAlign: "left" }}>
          <Row k="Reference" v={order.ref} />
          <Row k="Product" v={order.product} />
          <Row k="Spec" v={order.summary} />
          {!etsy && <Row k="Total" v={"$" + order.price} />}
        </div>
        <button className="btn btn-soft" style={{ width: "100%" }} onClick={onRestart}>
          <Icon name={etsy ? "Pencil" : "Plus"} size={17} /> {etsy ? "Make another edit" : "Design another"}
        </button>
      </div>
    </div>
  );
}
function Row({ k, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, fontSize: 13.5 }}>
      <span style={{ color: "var(--ink-3)", fontWeight: 600 }}>{k}</span>
      <span style={{ color: "var(--ink)", fontWeight: 700, textAlign: "right" }}>{v}</span>
    </div>
  );
}

Object.assign(window, { ReviewSheet, DoneScreen });
