/* Output flow: Download vs Print-it upsell (size → paper → frame → review → done) */
const { useState: useStateO, useEffect: useEffectOut } = React;
const { PS_DATA: DO } = window;

function PaperRow({ design, update }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {DO.PAPERS.map(p => {
        const active = design.paper === p.id;
        return (
          <button key={p.id} className={"tile" + (active ? " is-active" : "")} onClick={() => update({ paper: p.id })}
            style={{ padding: "13px 15px", display: "flex", alignItems: "center", gap: 13, border: "1.5px solid " + (active ? "var(--clay)" : "var(--line)"), textAlign: "left" }}>
            <span style={{ width: 30, height: 30, borderRadius: 7, flex: "none", background: p.id === "museum" ? "#F2ECDD" : p.id === "satin" ? "#FBF7EE" : "#F6F1E6", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.08)" }} />
            <span style={{ flex: 1, display: "flex", flexDirection: "column" }}>
              <span style={{ fontWeight: 700, fontSize: 14.5, color: "var(--ink)" }}>{p.label}</span>
              <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{p.sub}{p.add ? ` · +$${p.add}` : " · included"}</span>
            </span>
            {active && <Icon name="Check" size={18} style={{ color: "var(--clay)" }} />}
          </button>
        );
      })}
    </div>
  );
}

const PRINT_STEPS = [["paper", "Paper"], ["frame", "Frame"], ["review", "Review"]];

function OutputFlow({ design, update, entry, bp, onClose, onOrder, onCheckout }) {
  const [stage, setStage] = useStateO("size");
  const [done, setDone] = useStateO(null); // 'download' | 'print'
  const [busy, setBusy] = useStateO(false);
  const mobile = bp === "mobile";
  const size = DO.SIZES.find(s => s.id === design.size) || DO.SIZES[1];
  const paid = entry.paid || 0;
  const printTotal = DO.printPrice(design);
  const due = Math.max(0, printTotal - paid);

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

  const doDownload = async () => {
    setBusy(true);
    const name = (entry.orderRef || "poster") + "-" + size.id;
    try { await window.PS_EXPORT.downloadDesign(design, name); } catch (e) {}
    const order = DO.saveOrder({ ...DO.makeOrder(design, entry), status: "downloaded", kind: "download" });
    if (onOrder) onOrder(order);
    setBusy(false);
    setDone("download");
  };
  const payPrint = () => {
    const paperLabel = (DO.PAPERS.find(p => p.id === design.paper) || {}).label;
    const frameLabel = (DO.FRAMES.find(f => f.id === design.frame) || {}).label;
    const lineItem = { title: entry.productName + " — print",
      sub: size.label + " cm · " + paperLabel + " · " + frameLabel, design };
    if (onCheckout) { onCheckout({ subtotal: printTotal, lineItem }); return; }
    // fallback (no checkout host): file the order directly
    const order = DO.saveOrder({ ...DO.makeOrder(design, entry), status: "submitted", kind: "print", source: "print",
      product: lineItem.title, summary: lineItem.sub, price: due });
    if (onOrder) onOrder(order);
    setDone("print");
  };

  // ---- shell (sheet on mobile, dialog on desktop) ----
  const Shell = ({ children }) => (
    <div onClick={onClose} style={{ position: "absolute", inset: 0, zIndex: 50, display: "flex", alignItems: mobile ? "flex-end" : "center", justifyContent: "center", padding: mobile ? 0 : 16, background: "rgba(40,28,16,.46)", backdropFilter: "blur(3px)", animation: "fadeIn .2s" }}>
      <div onClick={e => e.stopPropagation()} role="dialog" aria-modal="true" className="scroll-y"
        style={{ width: mobile ? "100%" : "min(440px,100%)", maxHeight: mobile ? "88%" : "94%", overflowY: "auto",
          background: "var(--card)", border: "1px solid var(--line)",
          borderRadius: mobile ? "var(--r-xl) var(--r-xl) 0 0" : "var(--r-xl)",
          boxShadow: "var(--sh-lg)", animation: (mobile ? "sheetUp" : "riseIn") + " .28s var(--ease-out)" }}>
        {children}
      </div>
    </div>
  );

  // ---- DONE ----
  if (done) {
    const dl = done === "download";
    return (
      <Shell>
        <div style={{ textAlign: "center", padding: "32px 26px 26px" }}>
          <div style={{ width: 58, height: 58, borderRadius: "50%", background: "var(--sage-tint)", color: "#4A5436", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 16px" }}>
            <Icon name={dl ? "Download" : "Check"} size={30} stroke={2.3} />
          </div>
          <h2 style={{ fontFamily: "var(--serif)", fontSize: 25, fontWeight: 600, margin: "0 0 8px" }}>{dl ? "Your file is downloading" : "Print on the way!"}</h2>
          <p style={{ color: "var(--ink-2)", fontSize: 14, margin: "0 0 20px", lineHeight: 1.5 }}>
            {dl ? `A high-resolution ${size.label} cm PNG has been saved to your device.` : `We've charged the $${due} balance and sent your poster to print. A confirmation is on its way.`}
          </p>
          <button className="btn btn-soft" style={{ width: "100%" }} onClick={onClose}><Icon name="ArrowLeft" size={16} /> Back to editor</button>
        </div>
      </Shell>
    );
  }

  // ---- SIZE (entry step) ----
  if (stage === "size") {
    return (
      <Shell>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 22px 12px" }}>
          <span style={{ fontFamily: "var(--serif)", fontSize: 20, fontWeight: 600 }}>Choose your size</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: "0 22px 6px" }}>
          <p style={{ margin: "0 0 16px", fontSize: 13.5, color: "var(--ink-2)" }}>Download the digital file you bought, or upgrade to a framed print — your <b>${paid}</b> is credited.</p>
          <SizeRow design={design} update={update} />
        </div>
        <div style={{ position: "sticky", bottom: 0, background: "var(--card)", borderTop: "1px solid var(--line)", padding: "14px 22px", marginTop: 14, display: "flex", flexDirection: "column", gap: 10 }}>
          <button className="btn btn-soft" style={{ width: "100%" }} disabled={busy} onClick={doDownload}>
            <Icon name="Download" size={18} /> {busy ? "Preparing…" : `Download ${size.label} cm`}
          </button>
          <button className="btn btn-primary" style={{ width: "100%" }} onClick={() => setStage("paper")}>
            <Icon name="Printer" size={18} /> Print it — frame &amp; ship · from ${due}
          </button>
        </div>
      </Shell>
    );
  }

  // ---- PRINT path (paper / frame / review) ----
  const idx = PRINT_STEPS.findIndex(s => s[0] === stage);
  const back = () => idx === 0 ? setStage("size") : setStage(PRINT_STEPS[idx - 1][0]);
  const nextStage = idx < PRINT_STEPS.length - 1 ? PRINT_STEPS[idx + 1][0] : null;

  return (
    <Shell>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 18px 12px" }}>
        <button className="btn-icon btn-ghost" style={{ width: 34, height: 34, minHeight: 34 }} onClick={back}><Icon name="ArrowLeft" size={17} /></button>
        <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 6 }}>
          {PRINT_STEPS.map((s, i) => (
            <React.Fragment key={s[0]}>
              <span style={{ fontSize: 12.5, fontWeight: 700, color: i === idx ? "var(--clay-dark)" : i < idx ? "var(--ink-2)" : "var(--ink-3)" }}>{s[1]}</span>
              {i < PRINT_STEPS.length - 1 && <span style={{ flex: "none", width: 14, height: 2, borderRadius: 2, background: i < idx ? "var(--clay)" : "var(--line-2)" }} />}
            </React.Fragment>
          ))}
        </div>
        <button className="btn-icon btn-ghost" style={{ width: 34, height: 34, minHeight: 34 }} onClick={onClose}><Icon name="X" size={17} /></button>
      </div>

      <div className="scroll-y" style={{ padding: "6px 20px 16px", maxHeight: mobile ? "52vh" : "auto", overflowY: "auto" }}>
        {stage === "paper" && (<><H title="Choose your paper" /><PaperRow design={design} update={update} /></>)}
        {stage === "frame" && (<><H title="Add a frame" /><div style={{ padding: "4px 0" }}><FrameRow design={design} update={update} /></div><div style={{ marginTop: 16 }}><PhotoQualityNote design={design} /></div></>)}
        {stage === "review" && <PrintReview design={design} entry={entry} paid={paid} printTotal={printTotal} due={due} />}
      </div>

      <div style={{ position: "sticky", bottom: 0, background: "var(--card)", borderTop: "1px solid var(--line)", padding: "14px 20px" }}>
        {nextStage
          ? <button className="btn btn-primary" style={{ width: "100%" }} onClick={() => setStage(nextStage)}>Continue <Icon name="ArrowRight" size={17} /></button>
          : <button className="btn btn-primary" style={{ width: "100%" }} onClick={payPrint}><Icon name="ArrowRight" size={17} /> Checkout · balance ${due}</button>}
      </div>
    </Shell>
  );
}

function H({ title }) {
  return <h3 style={{ fontFamily: "var(--serif)", fontSize: 18, fontWeight: 600, margin: "2px 0 14px" }}>{title}</h3>;
}

function PrintReview({ design, entry, paid, printTotal, due }) {
  const size = DO.SIZES.find(s => s.id === design.size) || DO.SIZES[1];
  const paper = DO.PAPERS.find(p => p.id === design.paper) || DO.PAPERS[0];
  const frame = DO.FRAMES.find(f => f.id === design.frame) || DO.FRAMES[0];
  const rows = [
    ["Size", size.label + " cm"],
    ["Paper", paper.label + (paper.add ? ` (+$${paper.add})` : "")],
    ["Frame", frame.label + (frame.add ? ` (+$${frame.add})` : "")],
  ];
  return (
    <div>
      <div style={{ display: "flex", gap: 15, alignItems: "center", marginBottom: 16 }}>
        <Poster d={design} maxH={130} maxW={130 * size.ratio} />
        <div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 17, fontWeight: 600 }}>{entry.productName} — print</div>
          <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 3 }}>{size.label} cm · {paper.label} · {frame.label}</div>
        </div>
      </div>
      <div style={{ background: "var(--paper-2)", borderRadius: "var(--r-md)", padding: "4px 14px" }}>
        {rows.map(([k, v], i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", borderBottom: "1px solid var(--line)", fontSize: 13.5 }}>
            <span style={{ color: "var(--ink-3)", fontWeight: 600 }}>{k}</span><span style={{ color: "var(--ink)", fontWeight: 600 }}>{v}</span>
          </div>
        ))}
        <div style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", borderBottom: "1px solid var(--line)", fontSize: 13.5 }}>
          <span style={{ color: "var(--ink-3)", fontWeight: 600 }}>Print total</span><span style={{ color: "var(--ink)", fontWeight: 600 }}>${printTotal}</span>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", borderBottom: "1px solid var(--line)", fontSize: 13.5 }}>
          <span style={{ color: "var(--sage)", fontWeight: 700, display: "flex", alignItems: "center", gap: 6 }}><Icon name="BadgeCheck" size={14} /> Already paid on Etsy</span><span style={{ color: "var(--sage)", fontWeight: 700 }}>−${paid}</span>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "12px 0 8px" }}>
          <span style={{ fontSize: 14, fontWeight: 700, color: "var(--ink)" }}>Balance due</span>
          <span style={{ fontFamily: "var(--serif)", fontSize: 25, fontWeight: 600, color: "var(--ink)" }}>${due}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OutputFlow, PaperRow });
