/* OrchEcomm website — "Start for free" signup flow: modal form + success toast.
 * Controlled globally: window.OcSignup.open() from any CTA button. */
function SignupFlow() {
  const I = window.OcWebIcons;
  const [open, setOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  React.useEffect(() => {
    window.OcSignup = { open: () => setOpen(true) };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const onSuccess = (email) => {
    setOpen(false);
    setToast({ email });
    setTimeout(() => setToast(null), 5200);
  };

  return (
    <React.Fragment>
      {open ? <SignupModal onClose={() => setOpen(false)} onSuccess={onSuccess} /> : null}
      {toast ? <SignupToast email={toast.email} onClose={() => setToast(null)} /> : null}
    </React.Fragment>
  );
}

function SignupModal({ onClose, onSuccess }) {
  const I = window.OcWebIcons;
  const REVENUE = ["Less than $1,000", "$1,000 – $10,000", "$10,000 – $50,000", "$50,000 – $250,000", "$250,000+"];
  const SALES = ["1 – 50 orders", "50 – 250 orders", "250 – 1,000 orders", "1,000 – 5,000 orders", "5,000+ orders"];
  const PLATFORMS = [
    { id: "shopify", label: "Shopify", icon: "Bag" },
    { id: "woocommerce", label: "WooCommerce", icon: "Store" },
    { id: "stripe", label: "Stripe", icon: "Card" },
    { id: "paypal", label: "PayPal", icon: "Card" },
    { id: "magento", label: "Magento", icon: "Cart" },
    { id: "other", label: "Other", icon: "Plus" },
  ];

  const [form, setForm] = React.useState({ email: "", website: "", revenue: "", sales: "", platforms: [] });
  const [errors, setErrors] = React.useState({});
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const togglePlatform = (id) => setForm((f) => ({ ...f, platforms: f.platforms.includes(id) ? f.platforms.filter((p) => p !== id) : [...f.platforms, id] }));

  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!form.email.trim()) er.email = "Enter your email";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) er.email = "Enter a valid email";
    if (form.platforms.length === 0) er.platforms = "Select at least one platform";
    setErrors(er);
    if (Object.keys(er).length === 0) onSuccess(form.email.trim());
  };

  const labelStyle = { font: "var(--font-sans)", fontSize: 13, fontWeight: 600, color: "var(--ink-900)", marginBottom: 7, display: "block" };
  const fieldStyle = (err) => ({ width: "100%", height: 44, padding: "0 13px", border: "1px solid " + (err ? "var(--color-error)" : "var(--border-strong)"), borderRadius: "var(--radius-sm)", background: "var(--white)", font: "var(--font-sans)", fontSize: 15, color: "var(--ink-900)", outline: "none", boxSizing: "border-box" });
  const errText = (msg) => msg ? <div style={{ font: "var(--font-sans)", fontSize: 12, color: "var(--color-error)", marginTop: 5 }}>{msg}</div> : null;

  return (
    <div onMouseDown={onClose} style={{ position: "fixed", inset: 0, zIndex: 500, background: "rgba(27,67,50,0.45)", backdropFilter: "blur(3px)", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "40px 20px", overflowY: "auto" }} className="web-signup-overlay">
      <div onMouseDown={(e) => e.stopPropagation()} className="web-signup-card" style={{ width: 480, maxWidth: "100%", background: "var(--white)", borderRadius: "var(--radius-lg)", boxShadow: "0 24px 70px rgba(16,24,40,0.32)", overflow: "hidden", position: "relative" }}>
        {/* header */}
        <div style={{ position: "relative", padding: "26px 28px 22px", background: "linear-gradient(150deg, var(--green-800), var(--green-900))", color: "#fff", overflow: "hidden" }}>
          <div style={{ position: "absolute", inset: 0, opacity: 0.5, backgroundImage: "radial-gradient(circle at 1px 1px, rgba(255,255,255,0.14) 1px, transparent 0)", backgroundSize: "20px 20px" }} />
          <button onClick={onClose} aria-label="Close" style={{ position: "absolute", top: 16, right: 16, width: 34, height: 34, display: "inline-flex", alignItems: "center", justifyContent: "center", border: "none", borderRadius: "var(--radius-sm)", background: "rgba(255,255,255,0.14)", color: "#fff", cursor: "pointer" }}><I.X size={18} /></button>
          <div style={{ position: "relative" }}>
            <img src="../../assets/orchecomm-logo-white.svg" height="24" alt="OrchEcomm" />
            <h2 style={{ font: "var(--font-sans)", fontSize: 24, fontWeight: 700, letterSpacing: "-0.02em", color: "#fff", marginTop: 16 }}>Start for free</h2>
            <p style={{ font: "var(--font-sans)", fontSize: 14.5, lineHeight: 1.5, color: "var(--green-100)", marginTop: 6 }}>Tell us about your store and we'll set up your connected dashboard. No credit card required.</p>
          </div>
        </div>

        {/* form */}
        <form onSubmit={submit} style={{ padding: "24px 28px 28px" }}>
          <div style={{ marginBottom: 18 }}>
            <label style={labelStyle}>Work email <span style={{ color: "var(--color-error)" }}>*</span></label>
            <input type="email" value={form.email} onChange={(e) => set("email", e.target.value)} placeholder="you@yourstore.com" style={fieldStyle(errors.email)} />
            {errText(errors.email)}
          </div>

          <div style={{ marginBottom: 18 }}>
            <label style={labelStyle}>Store website</label>
            <input type="url" value={form.website} onChange={(e) => set("website", e.target.value)} placeholder="https://yourstore.com" style={fieldStyle(false)} />
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 18 }} className="web-signup-2col">
            <div>
              <label style={labelStyle}>Monthly revenue</label>
              <SelectField value={form.revenue} placeholder="Select range" options={REVENUE} onChange={(v) => set("revenue", v)} />
            </div>
            <div>
              <label style={labelStyle}>Monthly sales</label>
              <SelectField value={form.sales} placeholder="Select range" options={SALES} onChange={(v) => set("sales", v)} />
            </div>
          </div>

          <div style={{ marginBottom: 22 }}>
            <label style={labelStyle}>Platforms you use <span style={{ color: "var(--color-error)" }}>*</span></label>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 9 }} className="web-signup-2col">
              {PLATFORMS.map((p) => {
                const on = form.platforms.includes(p.id);
                return (
                  <button type="button" key={p.id} onClick={() => togglePlatform(p.id)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", border: "1.5px solid " + (on ? "var(--green-700)" : "var(--border-default)"), borderRadius: "var(--radius-sm)", background: on ? "var(--green-50)" : "var(--white)", cursor: "pointer", transition: "all var(--transition-fast)", textAlign: "left" }}>
                    <span style={{ width: 20, height: 20, borderRadius: 6, border: "1.5px solid " + (on ? "var(--green-700)" : "var(--border-strong)"), background: on ? "var(--green-700)" : "var(--white)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0, color: "#fff" }}>{on ? <I.Check size={13} /> : null}</span>
                    <span style={{ font: "var(--font-sans)", fontSize: 14, fontWeight: 500, color: on ? "var(--green-800)" : "var(--ink-800)" }}>{p.label}</span>
                  </button>
                );
              })}
            </div>
            {errText(errors.platforms)}
          </div>

          <button type="submit" style={{ width: "100%", height: 50, border: "none", borderRadius: "var(--radius-full)", background: "var(--green-800)", color: "#fff", font: "var(--font-sans)", fontSize: 16, fontWeight: 600, cursor: "pointer", boxShadow: "0 4px 14px rgba(45,106,79,0.28)", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, transition: "background var(--transition-fast)" }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--green-600)"} onMouseLeave={(e) => e.currentTarget.style.background = "var(--green-800)"}>
            Create my free account <I.ArrowRight size={17} />
          </button>
          <p style={{ textAlign: "center", font: "var(--font-sans)", fontSize: 12.5, color: "var(--text-muted)", marginTop: 14 }}>By continuing you agree to our Terms and Privacy Policy.</p>
        </form>
      </div>
      <style>{`
        .web-signup-card { animation: web-signup-in 0.32s var(--ease-out); }
        @keyframes web-signup-in { from { transform: translateY(18px) scale(0.98); } to { transform: none; } }
        @media (prefers-reduced-motion: reduce) { .web-signup-card { animation: none; } }
        @media (max-width: 520px) { .web-signup-2col { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

/* Custom select (native select styled to match the brand). */
function SelectField({ value, placeholder, options, onChange }) {
  const I = window.OcWebIcons;
  return (
    <div style={{ position: "relative" }}>
      <select value={value} onChange={(e) => onChange(e.target.value)} style={{ width: "100%", height: 44, padding: "0 36px 0 13px", border: "1px solid var(--border-strong)", borderRadius: "var(--radius-sm)", background: "var(--white)", font: "var(--font-sans)", fontSize: 14.5, color: value ? "var(--ink-900)" : "var(--text-muted)", outline: "none", appearance: "none", WebkitAppearance: "none", MozAppearance: "none", cursor: "pointer", boxSizing: "border-box" }}>
        <option value="" disabled>{placeholder}</option>
        {options.map((o) => <option key={o} value={o} style={{ color: "var(--ink-900)" }}>{o}</option>)}
      </select>
      <span style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", color: "var(--text-muted)", display: "inline-flex" }}><I.ChevronDown size={16} /></span>
    </div>
  );
}

function SignupToast({ email, onClose }) {
  const I = window.OcWebIcons;
  return (
    <div className="web-toast" style={{ position: "fixed", bottom: 24, right: 24, zIndex: 600, maxWidth: 380, display: "flex", alignItems: "flex-start", gap: 13, padding: "16px 18px", background: "var(--white)", border: "1px solid var(--border-default)", borderLeft: "4px solid var(--color-success)", borderRadius: "var(--radius-md)", boxShadow: "0 16px 44px rgba(16,24,40,0.22)" }}>
      <span style={{ width: 32, height: 32, borderRadius: "50%", background: "var(--color-success-bg)", color: "var(--color-success)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><I.Check size={18} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: "var(--font-sans)", fontSize: 15, fontWeight: 700, color: "var(--ink-900)" }}>You're in! 🎉</div>
        <div style={{ font: "var(--font-sans)", fontSize: 13.5, lineHeight: 1.5, color: "var(--text-secondary)", marginTop: 3 }}>We've sent a setup link to <b style={{ color: "var(--ink-800)" }}>{email}</b>. Check your inbox to connect your first platform.</div>
      </div>
      <button onClick={onClose} aria-label="Dismiss" style={{ border: "none", background: "transparent", color: "var(--text-muted)", cursor: "pointer", display: "inline-flex", flexShrink: 0 }}><I.X size={16} /></button>
      <style>{`
        .web-toast { animation: web-toast-in 0.4s var(--ease-out); }
        @keyframes web-toast-in { from { transform: translateX(20px); opacity: 0.4; } to { transform: none; opacity: 1; } }
        @media (prefers-reduced-motion: reduce) { .web-toast { animation: none; } }
      `}</style>
    </div>
  );
}

Object.assign(window, { SignupFlow, SignupModal, SignupToast, SelectField: SelectField });
