// Creator onboarding modal — 5 steps, one question per step.
// Steps: 1) Full name, 2) Primary social URL (+ add more), 3) Niche selection, 4) Email, 5) Confirmation.

function ApplyModal({ open, onClose }) {
  const [step, setStep] = React.useState(0);
  const [name, setName] = React.useState("");
  const [generation, setGeneration] = React.useState("");
  const [socials, setSocials] = React.useState([{ platform: "Instagram", url: "" }]);
  const [niches, setNiches] = React.useState([]);
  const [email, setEmail] = React.useState("");
  const [gdpr, setGdpr] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);

  // Reset on close
  React.useEffect(() => {
    if (!open) {
      setTimeout(() => {
        setStep(0); setName(""); setGeneration(""); setSocials([{ platform: "Instagram", url: "" }]); setNiches([]); setEmail(""); setGdpr(false); setSubmitted(false);
      }, 250);
    }
  }, [open]);

  // ESC to close
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [open, onClose]);

  if (!open) return null;

  const tint = STEP_TINTS[step];
  const onInk = step === 4;
  const fg = onInk ? "#fdf8f1" : C.ink;
  const fgMuted = onInk ? "rgba(253,248,241,0.55)" : C.muted;
  const fgBody = onInk ? "rgba(253,248,241,0.85)" : "#3a3530";
  const cardBorder = onInk ? "rgba(253,248,241,0.12)" : "rgba(29,26,23,0.10)";

  const NICHES = [
    "Food & drink", "Home & interiors", "Beauty", "Fashion",
    "Wellness", "Fitness", "Parenting", "Travel",
    "Tech & gadgets", "Lifestyle", "Pets", "Sustainability",
  ];

  const TOTAL = 5;
  const validName = name.trim().length > 1 && generation !== "";
  const validSocials = socials.filter((s) => s.url.trim().length > 4).length > 0;
  const validNiches = niches.length > 0;
  const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const validSubmit = validEmail && gdpr;

  const canAdvance = [validName, validSocials, validNiches, validSubmit][step];

  const next = () => {
    if (step < 3 && canAdvance) setStep(step + 1);
    else if (step === 3 && canAdvance) {
      setSubmitted(true);
      setStep(4);
    }
  };
  const back = () => { if (step > 0 && step < 4) setStep(step - 1); };

  const updateSocial = (i, field, v) => {
    const next = [...socials];
    next[i] = { ...next[i], [field]: v };
    setSocials(next);
  };
  const removeSocial = (i) => {
    if (socials.length === 1) return;
    setSocials(socials.filter((_, idx) => idx !== i));
  };
  const toggleNiche = (n) => {
    setNiches(niches.includes(n) ? niches.filter((x) => x !== n) : [...niches, n]);
  };

  const STEP_META = [
    { eyebrow: "01 / 05", q: "First, your name and age.", helper: "Real name. Pick the generation that fits — brands often brief by age range." },
    { eyebrow: "02 / 05", q: "Drop your social handles.", helper: "Paste the full profile URL. Add as many as you'd like — Instagram, TikTok, YouTube, Substack." },
    { eyebrow: "03 / 05", q: "What's your niche?", helper: "Pick all that genuinely fit. We'll only invite you to campaigns that match." },
    { eyebrow: "04 / 05", q: "Where should we email briefs?", helper: "We'll send active campaign briefs and your dashboard invite to this address." },
    { eyebrow: "05 / 05", q: "You're in the queue.", helper: "We review every applicant within 48 hours. Keep an eye on your inbox." },
  ];

  const meta = STEP_META[step];

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, background: "rgba(29,26,23,0.55)",
        backdropFilter: "blur(4px)", zIndex: 100,
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 24, fontFamily: "'Inter', system-ui, sans-serif",
        animation: "fadeIn .2s ease-out",
      }}
    >
      <style>{`
        @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(12px) } to { opacity: 1; transform: translateY(0) } }
        .apply-input::placeholder { color: rgba(29,26,23,0.35); }
        .apply-input:focus { outline: none; border-color: ${C.accent}; box-shadow: 0 0 0 4px rgba(217,79,42,0.12); }
        .apply-chip:hover { border-color: ${C.ink}; }
      `}</style>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: tint.bg, color: fg,
          borderRadius: 22, width: "100%", maxWidth: 600,
          padding: "0", overflow: "hidden", position: "relative",
          boxShadow: "0 40px 80px -20px rgba(29,26,23,0.5)",
          border: `1px solid ${cardBorder}`,
          animation: "slideUp .3s cubic-bezier(.2,.7,.3,1)",
          transition: "background .35s ease, color .35s ease",
        }}
      >
        {/* Progress bar */}
        <div style={{ height: 3, background: onInk ? "rgba(253,248,241,0.12)" : "rgba(29,26,23,0.08)", position: "relative" }}>
          <div style={{
            height: "100%", width: `${((step + 1) / TOTAL) * 100}%`,
            background: C.accent, transition: "width .3s ease",
          }}></div>
        </div>

        {/* Close */}
        <button onClick={onClose} aria-label="Close" style={{
          position: "absolute", top: 18, right: 18, background: "transparent",
          border: "none", cursor: "pointer", width: 32, height: 32,
          borderRadius: 999, display: "flex", alignItems: "center", justifyContent: "center",
          color: fgMuted, fontSize: 20, fontFamily: "inherit",
        }}>×</button>

        <div style={{ padding: "44px 44px 36px" }} key={step}>
          <div style={{
            fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
            letterSpacing: "0.18em", color: fgMuted, fontWeight: 700,
            textTransform: "uppercase",
          }}>{meta.eyebrow}</div>

          <h2 style={{
            fontFamily: "'Instrument Serif', serif", fontSize: 40,
            lineHeight: 1.1, fontWeight: 400, letterSpacing: "-0.02em",
            margin: "12px 0 8px", textWrap: "balance", color: fg,
          }}>{meta.q}</h2>
          <p style={{ fontSize: 14, color: fgMuted, margin: "0 0 28px", lineHeight: 1.5, maxWidth: 460 }}>{meta.helper}</p>

          {/* Step body */}
          <div style={{ minHeight: 180, animation: "slideUp .25s ease-out" }}>
            {step === 0 && (
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <input
                  className="apply-input"
                  autoFocus
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter" && canAdvance) next(); }}
                  placeholder="Maeve Cooper"
                  style={inputStyle}
                />
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {[
                    { id: "Gen Z", label: "Gen Z", sub: "18 – 27" },
                    { id: "Millennial", label: "Millennial", sub: "28 – 43" },
                    { id: "Gen X", label: "Gen X", sub: "44 – 59" },
                  ].map((g) => {
                    const on = generation === g.id;
                    return (
                      <button
                        key={g.id}
                        onClick={() => setGeneration(g.id)}
                        style={{
                          flex: "1 1 0", minWidth: 120,
                          padding: "14px 16px", borderRadius: 12,
                          border: `1.5px solid ${on ? C.ink : "rgba(29,26,23,0.15)"}`,
                          background: on ? C.ink : C.surface,
                          color: on ? C.paper : C.ink,
                          cursor: "pointer", textAlign: "left",
                          fontFamily: "inherit", transition: "all .15s ease",
                          display: "flex", flexDirection: "column", gap: 2,
                        }}
                      >
                        <span style={{ fontSize: 15, fontWeight: 600 }}>{g.label}</span>
                        <span style={{
                          fontFamily: "'JetBrains Mono', monospace",
                          fontSize: 11, letterSpacing: "0.05em",
                          opacity: on ? 0.7 : 0.55,
                        }}>{g.sub}</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {step === 1 && (
              <div>
                {socials.map((s, i) => (
                  <div key={i} style={{ display: "flex", gap: 8, marginBottom: 10 }}>
                    <div style={{ position: "relative", flexShrink: 0 }}>
                      <select
                        value={s.platform}
                        onChange={(e) => updateSocial(i, "platform", e.target.value)}
                        style={{
                          appearance: "none", WebkitAppearance: "none", MozAppearance: "none",
                          padding: "16px 36px 16px 16px", borderRadius: 12,
                          border: "1.5px solid rgba(29,26,23,0.15)",
                          background: "#ffffff", fontSize: 15, fontFamily: "'Inter', system-ui, sans-serif",
                          fontWeight: 500, color: C.ink, cursor: "pointer",
                          boxSizing: "border-box", height: "100%",
                        }}
                      >
                        {["Instagram", "TikTok", "YouTube", "Substack", "X / Twitter", "Threads", "LinkedIn", "Other"].map((p) => (
                          <option key={p} value={p}>{p}</option>
                        ))}
                      </select>
                      <span style={{
                        position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)",
                        pointerEvents: "none", color: C.muted, fontSize: 11,
                      }}>▾</span>
                    </div>
                    <input
                      className="apply-input"
                      autoFocus={i === socials.length - 1}
                      value={s.url}
                      onChange={(e) => updateSocial(i, "url", e.target.value)}
                      placeholder={i === 0 ? "Insert social handle URL" : "Add another"}
                      style={{ ...inputStyle, marginBottom: 0, flex: 1 }}
                    />
                    {socials.length > 1 && (
                      <button onClick={() => removeSocial(i)} aria-label="Remove" style={{
                        width: 56, borderRadius: 12, border: "1px solid rgba(29,26,23,0.15)",
                        background: C.surface, cursor: "pointer", color: C.muted,
                        fontFamily: "inherit", fontSize: 18, flexShrink: 0,
                      }}>−</button>
                    )}
                  </div>
                ))}
                <button onClick={() => setSocials([...socials, { platform: "TikTok", url: "" }])} style={{
                  display: "inline-flex", alignItems: "center", gap: 8,
                  padding: "10px 16px", borderRadius: 999,
                  background: "transparent", border: "1px dashed rgba(29,26,23,0.25)",
                  color: C.ink, fontSize: 13, fontWeight: 500, cursor: "pointer",
                  fontFamily: "inherit", marginTop: 4,
                }}>+ Add another handle</button>
              </div>
            )}

            {step === 2 && (
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {NICHES.map((n) => {
                  const on = niches.includes(n);
                  return (
                    <button
                      key={n}
                      className="apply-chip"
                      onClick={() => toggleNiche(n)}
                      style={{
                        padding: "10px 16px", borderRadius: 999,
                        border: `1px solid ${on ? C.ink : "rgba(29,26,23,0.18)"}`,
                        background: on ? C.ink : C.surface,
                        color: on ? C.paper : C.ink,
                        fontSize: 14, fontWeight: 500, cursor: "pointer",
                        fontFamily: "inherit", transition: "all .15s",
                      }}
                    >{on ? "✓ " : ""}{n}</button>
                  );
                })}
              </div>
            )}

            {step === 3 && (
              <div>
                <input
                  className="apply-input"
                  autoFocus
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter" && canAdvance) next(); }}
                  placeholder="hello@yourdomain.com"
                  style={inputStyle}
                />
                <label
                  htmlFor="gdpr-consent"
                  style={{
                    marginTop: 18, display: "flex", gap: 12, alignItems: "flex-start",
                    padding: "14px 16px", borderRadius: 12,
                    border: `1.5px solid ${gdpr ? C.ink : "rgba(29,26,23,0.15)"}`,
                    background: gdpr ? "rgba(29,26,23,0.04)" : C.surface,
                    cursor: "pointer", transition: "all .15s ease",
                    userSelect: "none",
                  }}
                >
                  <input
                    id="gdpr-consent"
                    type="checkbox"
                    checked={gdpr}
                    onChange={(e) => setGdpr(e.target.checked)}
                    style={{
                      width: 20, height: 20, marginTop: 1, flexShrink: 0,
                      accentColor: C.accent, cursor: "pointer",
                    }}
                  />
                  <span style={{ fontSize: 14, lineHeight: 1.5, color: "#3a3530" }}>
                    <b style={{ color: C.ink, fontWeight: 600 }}>Yes, I agree to GDPR.</b>{" "}
                    I've read the{" "}
                    <a
                      href="Giftfluence GDPR.html"
                      target="_blank"
                      rel="noopener"
                      onClick={(e) => e.stopPropagation()}
                      style={{ color: C.accent, fontWeight: 500, textDecoration: "underline", textUnderlineOffset: 2 }}
                    >UK GDPR Policy</a>{" "}
                    and consent to Giftfluence processing my personal data to coordinate gifting campaigns.
                  </span>
                </label>
              </div>
            )}

            {step === 4 && (
              <div style={{
                background: onInk ? "rgba(253,248,241,0.06)" : C.surface,
                border: `1px solid ${cardBorder}`,
                borderRadius: 14, padding: "24px 28px",
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: 999, background: C.accent,
                    color: C.ink, display: "flex", alignItems: "center", justifyContent: "center",
                    fontWeight: 700, fontSize: 16,
                  }}>✓</div>
                  <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22, letterSpacing: "-0.01em", color: fg }}>
                    Application received
                  </div>
                </div>
                <div style={{ fontSize: 14, color: fgBody, lineHeight: 1.6 }}>
                  Thanks, <b style={{ color: fg }}>{name || "creator"}</b>. We've logged your details and you're now in the review queue. We'll email <b style={{ color: fg }}>{email}</b> within 48 hours with next steps and your dashboard invite.
                </div>
                <div style={{
                  marginTop: 20, paddingTop: 18, borderTop: `1px dashed ${onInk ? "rgba(253,248,241,0.18)" : "rgba(29,26,23,0.15)"}`,
                  display: "flex", justifyContent: "space-between",
                  fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
                  color: fgMuted, letterSpacing: "0.05em",
                }}>
                  <span>// REF · GF-{(Math.random() * 9000 + 1000).toFixed(0)}</span>
                  <span>{niches.length} niche{niches.length === 1 ? "" : "s"} · {socials.filter(s => s.url.trim()).length} handle{socials.filter(s => s.url.trim()).length === 1 ? "" : "s"}</span>
                </div>
              </div>
            )}
          </div>

          {/* Footer actions */}
          <div style={{
            marginTop: 36, display: "flex", justifyContent: "space-between",
            alignItems: "center", gap: 16,
          }}>
            {step > 0 && step < 4 ? (
              <button onClick={back} style={{
                background: "transparent", border: "none", cursor: "pointer",
                color: fgMuted, fontSize: 14, fontWeight: 500, padding: "12px 0",
                fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 6,
              }}>← Back</button>
            ) : <div></div>}

            {step < 3 && (
              <button onClick={next} disabled={!canAdvance} style={{
                ...btnPrimary,
                opacity: canAdvance ? 1 : 0.4,
                cursor: canAdvance ? "pointer" : "not-allowed",
              }}>Continue →</button>
            )}
            {step === 3 && (
              <button onClick={next} disabled={!canAdvance} style={{
                ...btnPrimary,
                opacity: canAdvance ? 1 : 0.4,
                cursor: canAdvance ? "pointer" : "not-allowed",
              }}>Submit application →</button>
            )}
            {step === 4 && (
              <button onClick={onClose} style={{
                ...btnPrimary, background: C.accent, color: C.ink,
              }}>Close</button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

const STEP_TINTS = [
  { bg: "#fdf8f1", surface: "#ffffff" }, // paper / surface
  { bg: "#e3def7", surface: "#ffffff" }, // lavender
  { bg: "#d6ecdb", surface: "#ffffff" }, // mint
  { bg: "#f3eee2", surface: "#ffffff" }, // paper-2
  { bg: "#1d1a17", surface: "#fdf8f1" }, // ink (success)
];

const inputStyle = {
  width: "100%", padding: "16px 18px", borderRadius: 12,
  border: "1.5px solid rgba(29,26,23,0.15)",
  background: "#ffffff", fontSize: 17, fontFamily: "'Inter', system-ui, sans-serif",
  color: "#1d1a17", transition: "border-color .15s, box-shadow .15s",
  marginBottom: 4, boxSizing: "border-box", display: "block",
};

window.ApplyModal = ApplyModal;
