// Optimal Trade — New-Purchase wizard + AI agent negotiation scene
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

/* ============================== NEW-PURCHASE WIZARD ============================ */
function Wizard({ app }) {
  const [step, setStep] = useStateP(1);
  const [text, setText] = useStateP("");
  const [structured, setStructured] = useStateP(false);
  const [askAll, setAskAll] = useStateP(true);
  const [picked, setPicked] = useStateP([]);
  const [budget, setBudget] = useStateP(8000);
  const [weeks, setWeeks] = useStateP(4);
  const [more, setMore] = useStateP(false);
  const [incoterm, setIncoterm] = useStateP("FOB");
  const [sent, setSent] = useStateP(false);

  const recommended = SUPPLIERS.filter(s => s.authorized).slice(0, 4);
  const next = () => setStep(s => s + 1);
  const canNext = step === 1 ? (text.trim().length > 3) : step === 2 ? (askAll || picked.length > 0) : true;

  const submit = () => {
    if (askAll) { app.navigate("agent", { request: { text, budget, weeks, incoterm } }); }
    else { setSent(true); }
  };
  const toggle = (id) => setPicked(p => p.includes(id) ? p.filter(x => x !== id) : [...p, id]);

  if (sent) return (
    <div className="ot-screen"><StatusBar /><div className="ot-body"><div className="ot-pad" style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: "100%", textAlign: "center" }}>
      <span style={{ width: 84, height: 84, borderRadius: "50%", background: "var(--ot-orange-50)", color: "var(--ot-orange-deep)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="send" size={36} /></span>
      <h1 style={{ font: "var(--ot-h2)", margin: "20px 0 8px" }}>Request sent</h1>
      <p style={{ font: "var(--ot-body)", color: "var(--ot-fg-2)", maxWidth: 270, margin: 0 }}>Sent to {picked.length} suppliers. They usually answer within <b style={{ color: "var(--ot-navy)" }}>6 hours</b> — we'll notify you the moment offers arrive.</p>
      <div style={{ height: 24 }} />
      <Button variant="primary" icon="bell" onClick={() => app.setTab("orders")}>Track in Orders</Button>
      <button onClick={() => app.setTab("home")} style={ghostLink}>Close — we'll ping you</button>
    </div></div></div>
  );

  return (
    <div className="ot-screen">
      <StatusBar />
      <ScreenHead title="New purchase" onBack={step === 1 ? app.back : () => setStep(step - 1)} />
      {/* progress */}
      <div style={{ display: "flex", gap: 6, padding: "0 20px 14px" }}>
        {[1, 2, 3, 4].map(i => <span key={i} style={{ flex: 1, height: 4, borderRadius: 999, background: i <= step ? "var(--ot-orange)" : "var(--ot-gray-200)", transition: "background .3s" }} />)}
      </div>
      <div className="ot-body">
        <div className="ot-pad ot-page-anim" key={step} style={{ paddingTop: 0 }}>
          {step === 1 && <>
            <StepTitle n="1 of 4" t="What are you buying?" s="Describe it in your words — the agent structures the request for you." />
            <textarea value={text} onChange={e => setText(e.target.value)} placeholder="e.g. 50 industrial water pumps, 2.2kW, with CE certification"
              style={{ width: "100%", minHeight: 96, border: "1.5px solid var(--ot-gray-200)", borderRadius: "var(--ot-r-md)", padding: 14, font: "var(--ot-body)", color: "var(--ot-navy)", resize: "none", outline: "none", boxSizing: "border-box" }} />
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 12, padding: 16, border: "1.5px dashed var(--ot-gray-300)", borderRadius: "var(--ot-r-md)", color: "var(--ot-fg-2)", cursor: "pointer" }}>
              <Icon name="upload" size={20} /><span style={{ fontSize: 13.5, fontWeight: 600 }}>Attach spec or drawing (PDF, image)</span>
            </div>
            {text.trim().length > 3 && (
              <div className="ot-card ot-page-anim" style={{ marginTop: 14, padding: 14, border: "1.5px solid var(--ot-orange-200)", background: "var(--ot-orange-25)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
                  <Icon name="sparkles" size={16} style={{ color: "var(--ot-orange-deep)" }} />
                  <b style={{ fontWeight: 700, fontSize: 13, color: "var(--ot-navy)" }}>Agent structured your request</b>
                </div>
                <KV k="Product" v="Industrial water pumps" />
                <KV k="Quantity" v="50 units" />
                <KV k="Spec" v="2.2 kW · CE certified" last />
                <p style={{ fontSize: 12, color: "var(--ot-fg-2)", margin: "10px 0 0" }}>Confirm or edit on the next steps — no 10-field forms.</p>
              </div>
            )}
          </>}

          {step === 2 && <>
            <StepTitle n="2 of 4" t="Who should quote?" s="Recommended verified suppliers for this category." />
            <label onClick={() => setAskAll(v => !v)} style={{ display: "flex", alignItems: "center", gap: 12, padding: 14, borderRadius: "var(--ot-r-md)", border: `1.5px solid ${askAll ? "var(--ot-orange)" : "var(--ot-gray-200)"}`, background: askAll ? "var(--ot-orange-25)" : "#fff", cursor: "pointer", marginBottom: 14 }}>
              <span style={{ width: 40, height: 40, borderRadius: 12, background: "var(--ot-navy)", color: "var(--ot-orange-300)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="sparkles" size={20} /></span>
              <span style={{ flex: 1 }}><b style={{ display: "block", fontWeight: 700, fontSize: 14.5, color: "var(--ot-navy)" }}>Let the agent ask all suitable</b><span style={{ fontSize: 12.5, color: "var(--ot-fg-2)" }}>Negotiates in parallel, returns a comparison</span></span>
              <Toggle on={askAll} />
            </label>
            <div className={"ot-card" + (askAll ? "" : "")} style={{ opacity: askAll ? .5 : 1, pointerEvents: askAll ? "none" : "auto" }}>
              {recommended.map(s => (
                <Row key={s.id} iconEl={<Flag code={s.flag} size={42} />} title={s.name} sub={`${s.country} · ★ ${s.rating}`}
                  onClick={() => toggle(s.id)}
                  right={<span style={{ width: 24, height: 24, borderRadius: 8, border: `2px solid ${picked.includes(s.id) ? "var(--ot-orange)" : "var(--ot-gray-300)"}`, background: picked.includes(s.id) ? "var(--ot-orange)" : "#fff", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", marginRight: 4 }}>{picked.includes(s.id) && <Icon name="check" size={14} strokeWidth={3} />}</span>} />
              ))}
            </div>
          </>}

          {step === 3 && <>
            <StepTitle n="3 of 4" t="Budget & timing" s="Just the essentials. Everything else has smart defaults." />
            <div className="ot-field" style={{ marginBottom: 16 }}>
              <label>Target budget (USD)</label>
              <div className="ot-input"><span style={{ fontWeight: 700 }}>$</span><input value={fmt(budget)} onChange={e => setBudget(+e.target.value.replace(/[^0-9]/g, "") || 0)} /></div>
            </div>
            <div className="ot-field" style={{ marginBottom: 16 }}>
              <label>Need it within</label>
              <div className="ot-seg">{[2, 4, 6].map(wk => <button key={wk} className={weeks === wk ? "active" : ""} onClick={() => setWeeks(wk)}>{wk} weeks</button>)}</div>
            </div>
            <button onClick={() => setMore(v => !v)} style={{ display: "flex", alignItems: "center", gap: 6, background: "none", border: "none", color: "var(--ot-orange-deep)", fontWeight: 700, fontSize: 13.5, cursor: "pointer", padding: "4px 0" }}>
              <Icon name={more ? "chevron-up" : "chevron-down"} size={16} />More options
            </button>
            {more && <div className="ot-page-anim" style={{ marginTop: 8 }}>
              <label style={{ fontWeight: 600, fontSize: 12.5, color: "var(--ot-fg-2)", display: "block", marginBottom: 8 }}>Incoterm</label>
              <div className="ot-seg">{["FOB", "CIF", "EXW"].map(t => <button key={t} className={incoterm === t ? "active" : ""} onClick={() => setIncoterm(t)}>{t}</button>)}</div>
            </div>}
          </>}

          {step === 4 && <>
            <StepTitle n="4 of 4" t="Review & send" s="" />
            <div className="ot-card flat" style={{ padding: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}><Icon name="sparkles" size={16} style={{ color: "var(--ot-orange-deep)" }} /><b style={{ fontWeight: 700, fontSize: 14, color: "var(--ot-navy)" }}>Quote request</b></div>
              <KV k="Item" v="Industrial water pumps ×50" />
              <KV k="Budget" v={money("$", budget)} />
              <KV k="Timeline" v={`${weeks} weeks`} />
              <KV k="Incoterm" v={incoterm} />
              <KV k="Suppliers" v={askAll ? "All suitable (agent)" : `${picked.length} selected`} last />
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 14, color: "var(--ot-fg-2)", fontSize: 12.5 }}>
              <Icon name="shield" size={15} style={{ color: "var(--ot-success)" }} />Protected by mandate contract · no payment until you accept an offer
            </div>
          </>}
        </div>
      </div>
      <div style={{ padding: "12px 20px 26px", background: "#fff", borderTop: "1px solid var(--ot-gray-100)" }}>
        {step < 4
          ? <Button variant="primary" disabled={!canNext} onClick={next}>Continue</Button>
          : <Button variant="primary" icon={askAll ? "sparkles" : "send"} onClick={submit}>{askAll ? "Start agent negotiation" : "Send request"}</Button>}
      </div>
    </div>
  );
}
function StepTitle({ n, t, s }) {
  return <div style={{ marginBottom: 16 }}>
    <span style={{ fontWeight: 700, fontSize: 11.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ot-orange-deep)" }}>Step {n}</span>
    <h2 style={{ font: "var(--ot-h2)", margin: "6px 0 4px" }}>{t}</h2>
    {s && <p style={{ font: "var(--ot-body-sm)", color: "var(--ot-fg-2)", margin: 0 }}>{s}</p>}
  </div>;
}
function Toggle({ on }) {
  return <span style={{ width: 46, height: 28, borderRadius: 999, background: on ? "var(--ot-orange)" : "var(--ot-gray-300)", position: "relative", flex: "none", transition: "background .2s" }}>
    <span style={{ position: "absolute", top: 3, left: on ? 21 : 3, width: 22, height: 22, borderRadius: "50%", background: "#fff", transition: "left .2s var(--ot-spring)" }} /></span>;
}
const ghostLink = { marginTop: 14, background: "none", border: "none", color: "var(--ot-fg-2)", fontWeight: 600, fontSize: 14, cursor: "pointer", fontFamily: "var(--ot-font-body)" };

Object.assign(window, { Wizard, StepTitle, Toggle, ghostLink });
