const CALENDLY_URL = "https://calendly.com/stanzin_tundup/30min";

function loadCalendlyWidget() {
  if (!document.getElementById("calendly-widget-css")) {
    const link = document.createElement("link");
    link.id = "calendly-widget-css";
    link.href = "https://assets.calendly.com/assets/external/widget.css";
    link.rel = "stylesheet";
    document.head.appendChild(link);
  }

  if (window.Calendly?.initPopupWidget) return Promise.resolve();

  const existingScript = document.getElementById("calendly-widget-js");
  if (existingScript) {
    return new Promise((resolve) => {
      existingScript.addEventListener("load", resolve, { once: true });
      setTimeout(resolve, 1200);
    });
  }

  return new Promise((resolve) => {
    const script = document.createElement("script");
    script.id = "calendly-widget-js";
    script.src = "https://assets.calendly.com/assets/external/widget.js";
    script.type = "text/javascript";
    script.async = true;
    script.addEventListener("load", resolve, { once: true });
    script.addEventListener("error", resolve, { once: true });
    document.body.appendChild(script);
  });
}

function openCalendlyStrategyCall() {
  loadCalendlyWidget().then(() => {
    if (window.Calendly?.initPopupWidget) {
      window.Calendly.initPopupWidget({ url: CALENDLY_URL });
      return;
    }

    window.open(CALENDLY_URL, "_blank", "noopener,noreferrer");
  });
}

window.openCalendlyStrategyCall = openCalendlyStrategyCall;

function ContactPage({ onGo }) {
  const [form, setForm] = useState({ name: "", email: "", company: "", budget: "", req: "", type: "Growth Consulting" });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    loadCalendlyWidget();
  }, []);

  function setField(k, v) {
    setForm((f) => ({ ...f, [k]: v }));
    setErrors((e) => ({ ...e, [k]: null }));
  }
  function validate() {
    const e = {};
    if (!form.name.trim()) e.name = "Required";
    if (!form.email.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)) e.email = "Valid email required";
    if (!form.req.trim()) e.req = "Tell me a bit about what you're working on";
    return e;
  }
  async function submit(ev) {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length !== 0) return;

    setLoading(true);
    setError(null);

    try {
      const res = await fetch('/api/contact.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });

      const contentType = res.headers.get('content-type') || '';
      const data = contentType.includes('application/json') ? await res.json() : null;

      if (!res.ok) {
        throw new Error(data?.error || `Submission failed (${res.status})`);
      }
      if (!data?.ok) throw new Error('Submission endpoint did not confirm delivery');

      setSent(true);
      setForm({ name: "", email: "", company: "", budget: "", req: "", type: "Growth Consulting" });
    } catch (err) {
      setError(err.message || 'Submission failed. Please try again later.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      <section className="wrap">
        <div className="contact">
          <div>
            <Reveal><span className="hero__kicker">Contact · say hi</span></Reveal>
            <Reveal delay={80}>
              <h1 className="contact__title" style={{ marginTop: 24 }}>
                Tell me what you're <em>building</em>.
              </h1>
            </Reveal>
            <Reveal delay={160}>
              <p className="contact__lede">
                A few lines is enough. I read every message and reply within 24 hours, IST working days.
                If it's a fit, we'll jump on a 30-minute call — no obligation, no sales deck.
              </p>
            </Reveal>
            <Reveal delay={220}>
              <dl className="contact__list">
                <div>
                  <dt>Email</dt>
                  <dd>hello@stanzin.me</dd>
                </div>
                <div>
                  <dt>Calendly</dt>
                  <dd>
                    <a
                      href={CALENDLY_URL}
                      onClick={(e) => {
                        e.preventDefault();
                        openCalendlyStrategyCall();
                      }}
                      style={{ borderBottom: "1px solid", cursor: "pointer" }}
                    >
                      Strategy Call with Stanzin
                    </a>
                  </dd>
                </div>
                <div>
                  <dt>Elsewhere</dt>
                  <dd>LinkedIn · X · Substack</dd>
                </div>
                <div>
                  <dt>Reply time</dt>
                  <dd>Within 24h, IST working days</dd>
                </div>
              </dl>
            </Reveal>
          </div>

          <Reveal delay={260}>
            {sent ?
            <div className="form__sent">
                <h3>Message sent.</h3>
                <p>I'll get back to you within 24 hours. Meanwhile, check <a onClick={() => onGo("insights")} style={{ borderBottom: "1px solid var(--accent)", color: "var(--accent)", cursor: "pointer" }}>Insights</a>.</p>
              </div> :

            <form className="form" onSubmit={submit} noValidate>
                <div className={"field" + (errors.name ? " field--error" : "")}>
                  <label>Name</label>
                  <input value={form.name} onChange={(e) => setField("name", e.target.value)} placeholder="Your full name" />
                  {errors.name && <span className="field__err">{errors.name}</span>}
                </div>
                <div className={"field" + (errors.email ? " field--error" : "")}>
                  <label>Email</label>
                  <input type="email" value={form.email} onChange={(e) => setField("email", e.target.value)} placeholder="you@company.com" />
                  {errors.email && <span className="field__err">{errors.email}</span>}
                </div>
                <div className="field">
                  <label>Company (optional)</label>
                  <input value={form.company} onChange={(e) => setField("company", e.target.value)} placeholder="Your brand or company" />
                </div>
                <div className="field">
                  <label>What do you need help with?</label>
                  <div className="chips">
                    {["Growth Consulting", "Performance Marketing", "Funnel Optimization", "SEO Strategy", "Hiring"].map((t) =>
                  <button type="button" key={t} className={form.type === t ? "is-active" : ""} onClick={() => setField("type", t)}>{t}</button>
                  )}
                  </div>
                </div>
                <div className="field">
                  <label>Monthly budget (optional)</label>
                  <div className="chips">
                    {["< ₹1L", "₹1–3L", "₹3–6L", "₹6L+", "Not sure"].map((t) =>
                  <button type="button" key={t} className={form.budget === t ? "is-active" : ""} onClick={() => setField("budget", t)}>{t}</button>
                  )}
                  </div>
                </div>
                <div className={"field" + (errors.req ? " field--error" : "")}>
                  <label>Tell me about it</label>
                  <textarea value={form.req} onChange={(e) => setField("req", e.target.value)} placeholder="The problem, the context, the timeline. Bullet points are fine." />
                  {errors.req && <span className="field__err">{errors.req}</span>}
                </div>
                <button className="btn btn--accent form__submit" type="submit" disabled={loading}>
                  {loading ? 'Sending…' : 'Send message'} <span className="arr">↗</span>
                </button>
                {error && <div className="form__error">{error}</div>}
              </form>
            }
          </Reveal>
        </div>
      </section>

      <section className="cta-big" style={{ paddingTop: 80, paddingBottom: 80 }}>
        <div className="wrap">
          <Reveal><h2 className="cta-big__title" style={{ fontSize: "clamp(36px, 5vw, 72px)" }}>Prefer a <em>call?</em></h2></Reveal>
          <Reveal delay={100}>
            <div className="cta-big__row">
              <button className="btn btn--primary" onClick={openCalendlyStrategyCall}>Book 30 min ↗</button>
              <button className="btn btn--ghost" onClick={() => alert("Resume placeholder")}>Download resume ↓</button>
            </div>
          </Reveal>
        </div>
      </section>
    </>);

}

window.ContactPage = ContactPage;
