const { useState, useEffect, useRef } = React;

const TIMING_OPTIONS = [
  { id: "immediate",   label: "Immediate",       sub: "Hiring this month" },
  { id: "next-month",  label: "Next month",      sub: "~30 days out" },
  { id: "3-months",    label: "In 3 months",     sub: "Building the role" },
  { id: "longer",      label: "Longer term",     sub: "Exploring options" },
];

const FUNDING_OPTIONS = [
  { id: "pre-seed", label: "Pre-seed" },
  { id: "seed",     label: "Seed" },
  { id: "series-a", label: "Series A" },
  { id: "series-b", label: "Series B" },
  { id: "all-above", label: "All of the above" },
];

function IntakeModal({ open, onClose, source }) {
  const [company, setCompany] = useState("");
  const [timing, setTiming] = useState(null);
  const [funding, setFunding] = useState(null);
  const [email, setEmail] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const firstInput = useRef(null);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    setTimeout(() => firstInput.current && firstInput.current.focus(), 60);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  useEffect(() => {
    if (open) {
      setSubmitted(false);
      setCompany("");
      setTiming(null);
      setFunding(null);
      setEmail("");
    }
  }, [open]);

  if (!open) return null;

  const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const canSubmit = company.trim().length > 1 && timing && funding && validEmail;

  const submit = async (e) => {
    e.preventDefault();
    if (!canSubmit) return;
    try {
      await fetch("/api/intake", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ company, timing, funding, email, cta_source: source }),
      });
    } catch (_) {}
    setSubmitted(true);
  };

  return (
    <div className="modal-backdrop" onClick={onClose} role="dialog" aria-modal="true">
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <span className="live"><span className="dot"></span>NEW.MOAT · FOUNDING COHORT</span>
          <button className="close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
            </svg>
          </button>
        </div>

        {submitted ? (
          <div className="modal-body">
            <div className="success">
              <div className="check">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                  <path d="M4 10.5L8 14.5L16 6.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <h4>Check your email.</h4>
              <p>Your private link is on the way to <strong>{email}</strong>.</p>
              <p style={{marginTop: 10, fontSize: 13, color: "var(--ink-500)", lineHeight: 1.6}}>
                It's a 5-minute AI conversation — you'll walk away knowing exactly who you need to hire. We'll follow up if there's a fit.
              </p>
            </div>
          </div>
        ) : (
          <form className="modal-body" onSubmit={submit}>
            <div style={{marginBottom: 20}}>
              <h3 style={{margin: "0 0 8px", fontSize: 20, fontWeight: 600, letterSpacing: "-0.01em", color: "var(--ink)", textDecoration: "underline", textUnderlineOffset: "4px"}}>
                Get your private link 🔗
              </h3>
              <p style={{margin: 0, fontSize: 14, color: "var(--ink-500)", lineHeight: 1.6}}>
                We'll send it within a few hours. Your link opens a 5-minute AI session that maps the role you actually need — stage fit, output bar, gaps in your current team. No sales call. No follow-up until you want one.
              </p>
            </div>

            <div className="field">
              <label className="field-label" htmlFor="im-company">Company <span className="req">*</span></label>
              <input
                ref={firstInput}
                id="im-company"
                className="field-input"
                placeholder="e.g. Anthropic, Ramp, your startup"
                value={company}
                onChange={(e) => setCompany(e.target.value)}
                autoComplete="organization"
              />
            </div>

            <div className="field">
              <label className="field-label">When do you need to hire? <span className="req">*</span></label>
              <div className="field-list">
                {TIMING_OPTIONS.map((o) => (
                  <button
                    type="button"
                    key={o.id}
                    className={"field-row" + (timing === o.id ? " on" : "")}
                    onClick={() => setTiming(o.id)}
                  >
                    <span className="field-row-dot"></span>
                    <span>{o.label} <span className="field-row-sub">{o.sub}</span></span>
                  </button>
                ))}
              </div>
            </div>

            <div className="field">
              <label className="field-label">Funding stage <span className="req">*</span></label>
              <div className="field-list">
                {FUNDING_OPTIONS.map((o) => (
                  <button
                    type="button"
                    key={o.id}
                    className={"field-row" + (funding === o.id ? " on" : "")}
                    onClick={() => setFunding(o.id)}
                  >
                    <span className="field-row-dot"></span>
                    <span>{o.label}</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="field">
              <label className="field-label" htmlFor="im-email">Work email <span className="req">*</span></label>
              <input
                id="im-email"
                type="email"
                className="field-input"
                placeholder="you@company.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                autoComplete="email"
              />
            </div>

            <div className="modal-foot" style={{margin: "20px -22px -22px", borderRadius: "0 0 14px 14px"}}>
              <span className="note">Serious founders only.</span>
              <button className="modal-submit" type="submit" disabled={!canSubmit}>
                Send me the link <span>→</span>
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

window.IntakeModal = IntakeModal;
