// Olga Moreno landing — shared components

const { useState, useEffect, useRef, useCallback } = React;

// ── Placeholder block ────────────────────────────────────────────────
function Placeholder({ caption, children, className = "", style = {} }) {
  return (
    <div className={`ph ${className}`} style={style}>
      {caption && <span className="ph-caption">{caption}</span>}
      {children}
    </div>
  );
}

// ── Reveal on scroll ────────────────────────────────────────────────
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            el.classList.add("in");
            obs.unobserve(el);
          }
        });
      },
      { threshold: 0.15 }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return ref;
}

// ── Arrow ───────────────────────────────────────────────────────────
function Arrow({ size = 14 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M1 7h12M8 2l5 5-5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

const CLIENT_REDIRECT_URL = "https://olgamorenorealestate.com";
const JOTFORM_WIDGET_ID = "JFWebsiteWidget-019dc5d474b17716a6e9079ead69db062af6";
const JOTFORM_WIDGET_SCRIPT = "https://www.jotform.com/website-widgets/embed/019dc5d474b17716a6e9079ead69db062af6";

// ── Reviews widget ─────────────────────────────────────────────────
function ReviewsWidget() {
  useEffect(() => {
    const existing = document.querySelector(`script[data-jotform-widget="${JOTFORM_WIDGET_ID}"]`);
    if (existing) existing.remove();

    const script = document.createElement("script");
    script.src = JOTFORM_WIDGET_SCRIPT;
    script.async = true;
    script.dataset.jotformWidget = JOTFORM_WIDGET_ID;
    document.body.appendChild(script);

    return () => {
      script.remove();
    };
  }, []);

  return <div className="reviews-widget" id={JOTFORM_WIDGET_ID} aria-label="Google reviews" />;
}

// ── Animated hero prompt (typewriter in a pill) ─────────────────────
function HeroPrompt({ text }) {
  const [shown, setShown] = useState(0);
  const [pillOpen, setPillOpen] = useState(false);

  useEffect(() => {
    // open the pill first
    const openT = setTimeout(() => setPillOpen(true), 200);
    return () => clearTimeout(openT);
  }, []);

  useEffect(() => {
    if (!pillOpen) return;
    if (shown >= text.length) return;
    const t = setTimeout(() => setShown((s) => s + 1), 110);
    return () => clearTimeout(t);
  }, [pillOpen, shown, text]);

  return (
    <div className={"hero-prompt" + (pillOpen ? " open" : "")} role="status">
      <span className="hero-prompt-text">
        {text.slice(0, shown)}
        {pillOpen && shown < text.length && <span className="hero-prompt-caret" />}
      </span>
    </div>
  );
}

// ── Nav ─────────────────────────────────────────────────────────────
function Nav({ onReset, choice }) {
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="#top" className="logo" onClick={(e) => { if (choice) { e.preventDefault(); onReset(); } }}>
          <span className="logo-mark">O</span>
          <span>Olga Moreno</span>
        </a>
        <div className="nav-links">
          {choice && <button className="nav-reset" onClick={onReset}>← Start over</button>}
        </div>
      </div>
    </nav>
  );
}

// ── Contact Forms ───────────────────────────────────────────────────

function ContactForm({ variant, ctaCopy }) {
  const [form, setForm] = useState({
    name: "", email: "", phone: "", youtube: "", message: "",
  });
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    if (!submitted || variant !== "client") return;
    const redirectTimer = setTimeout(() => {
      window.location.href = CLIENT_REDIRECT_URL;
    }, 6000);
    return () => clearTimeout(redirectTimer);
  }, [submitted, variant]);

  const upd = (k) => (e) => {
    setForm((f) => ({ ...f, [k]: e.target.value }));
    if (errors[k]) setErrors((er) => ({ ...er, [k]: null }));
  };

  const isValidEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(value.trim());
  const isValidPhone = (value) => {
    const phone = value.trim();
    const digits = value.replace(/\D/g, "");
    const hasValidChars = /^[+\d\s().-]+$/.test(phone);
    const hasValidPlus = !phone.includes("+") || (phone.startsWith("+") && phone.indexOf("+", 1) === -1);
    return hasValidChars && hasValidPlus && digits.length >= 7 && digits.length <= 15;
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Required";
    if (!form.email.trim()) e.email = "Required";
    else if (!isValidEmail(form.email)) e.email = "Enter a valid email";
    if (!form.phone.trim()) e.phone = "Required";
    else if (!isValidPhone(form.phone)) e.phone = "Enter a valid phone number";
    return e;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setSubmitting(true);

    try {
      const res = await fetch("/api/lead", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          type: variant,
          name: form.name,
          email: form.email,
          phone: form.phone,
          youtube: form.youtube,
          message: form.message,
        }),
      });

      if (!res.ok) {
        throw new Error("Lead submission failed");
      }

      setSubmitting(false);
      setSubmitted(true);
    } catch (err) {
      setSubmitting(false);
      setErrors((current) => ({
        ...current,
        form: "We couldn't send that. Please try again in a moment.",
      }));
    }
  };

  if (submitted) {
    return (
      <div className="form-card form-success">
        <div style={{ fontSize: 56, marginBottom: 8, color: "var(--accent)" }}>✦</div>
        <h3>You're in, {form.name.split(" ")[0]}.</h3>
        <p className="muted" style={{ maxWidth: "36ch", margin: "0 auto 24px" }}>
          Olga will reach out to <b style={{ color: "var(--ink)" }}>{form.email}</b> within 24 hours.
        </p>
        <div className="eyebrow">
          {variant === "client" ? "Redirecting in a few seconds" : "Check your inbox · and your spam folder"}
        </div>
      </div>
    );
  }

  return (
    <form className="form-card" onSubmit={submit} noValidate>
      <div className="form-row">
        <div className="field">
          <label>Name</label>
          <input type="text" value={form.name} onChange={upd("name")}
            required
            aria-invalid={!!errors.name} placeholder="Jordan Ramirez" />
          {errors.name && <div className="err">{errors.name}</div>}
        </div>
        <div className="field">
          <label>Email</label>
          <input type="email" value={form.email} onChange={upd("email")}
            required inputMode="email" autoComplete="email"
            aria-invalid={!!errors.email} placeholder="you@example.com" />
          {errors.email && <div className="err">{errors.email}</div>}
        </div>
      </div>

      <div className="form-row single">
        <div className="field">
          <label>Phone</label>
          <input type="tel" value={form.phone} onChange={upd("phone")}
            required inputMode="tel" autoComplete="tel"
            aria-invalid={!!errors.phone} placeholder="(725) 215-2154" />
          {errors.phone && <div className="err">{errors.phone}</div>}
        </div>
      </div>

      {variant === "realtor" ? (
        <div className="form-row single">
          <div className="field">
            <label>Link to current YouTube channel</label>
            <input type="url" value={form.youtube} onChange={upd("youtube")}
              placeholder="youtube.com/@yourhandle (optional — haven't started? leave blank)" />
          </div>
        </div>
      ) : (
        <div className="form-row single">
          <div className="field">
            <label>Message</label>
            <textarea rows="4" value={form.message} onChange={upd("message")}
              placeholder="Tell Olga what you're looking for — buying, selling, timeline, neighborhoods…" />
          </div>
        </div>
      )}

      <button type="submit" className="form-submit" disabled={submitting}>
        {submitting ? "Sending…" : ctaCopy}
      </button>
      {errors.form && <div className="form-error">{errors.form}</div>}
    </form>
  );
}

// ── Hero ────────────────────────────────────────────────────────────
function Hero({ tweaks, choice, onChoose, onReset }) {
  const [hover, setHover] = useState(null);

  useEffect(() => {
    if (!choice || typeof window === "undefined") return;
    if (!window.matchMedia("(max-width: 900px)").matches) return;

    const scrollT = setTimeout(() => {
      document.querySelector(".chosen-form")?.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }, 650);

    return () => clearTimeout(scrollT);
  }, [choice]);

  return (
    <section className={"hero hero-v2" + (choice ? " has-choice" : "")} id="top"
             data-choice={choice || "none"}>
      {/* Big photo */}
      <div className="hero-photo">
        <img src="assets/olga-portrait.jpg" alt="Olga Moreno" />
        <div className="hero-photo-grad" />
      </div>

      {/* Initial state: two big buttons */}
      {!choice && (
        <div className="hero-choose">
          <div className="hero-choose-inner">
            <HeroPrompt text="Which one are you?" />
            <div className="hero-choose-btns">
              <button
                className={"choose-btn choose-realtor" + (hover === "realtor" ? " hot" : "")}
                onMouseEnter={() => setHover("realtor")}
                onMouseLeave={() => setHover(null)}
                onClick={() => onChoose("realtor")}
              >
                <span className="choose-btn-label">I'm a Realtor</span>
                <span className="choose-btn-sub">YouTube Mastermind</span>
                <Arrow size={16} />
              </button>
              <button
                className={"choose-btn choose-client" + (hover === "client" ? " hot" : "")}
                onMouseEnter={() => setHover("client")}
                onMouseLeave={() => setHover(null)}
                onClick={() => onChoose("client")}
              >
                <span className="choose-btn-label">I want to buy or sell</span>
                <span className="choose-btn-sub">Las Vegas home</span>
                <Arrow size={16} />
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Chosen state — animates in */}
      {choice === "realtor" && (
        <ChosenPanel
          variant="realtor"
          tweaks={tweaks}
          onReset={onReset}
          eyebrow="Free · Invite-only Mastermind"
          heading={<>Join my YouTube<br />Mastermind for Realtors</>}
          copy={<>
            Zero paid ads, zero cold calls. I'll show you the exact system that
            took me from a brand new Realtor, with no client-list, to a Top 1%
            Agent with over $500K in GCI in my first 2 years.
          </>}
          stats={[
            { num: "16K", label: "Subscribers" },
            { num: "2M+", label: "Views" },
            { num: "$500K", label: "GCI in 24mo" },
          ]}
          ctaCopy={tweaks.realtorCTA}
        />
      )}

      {choice === "client" && (
        <ChosenPanel
          variant="client"
          tweaks={tweaks}
          onReset={onReset}
          eyebrow="Las Vegas · Nevada"
          heading={<>Let's get you<br />home.</>}
          copy={<>
            Buying, selling, or relocating to Vegas? Same attention to detail you
            see on YouTube, applied to your closing.
          </>}
          ctaCopy={tweaks.clientCTA || "Get in touch →"}
        />
      )}
    </section>
  );
}

// ── Chosen panel (slides in under hero photo) ──────────────────────
function ChosenPanel({ variant, tweaks, onReset, eyebrow, heading, copy, stats, ctaCopy }) {
  return (
    <div className="chosen-panel">
      <div className="chosen-inner">
        <button className="chosen-back" onClick={onReset} aria-label="Back">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M13 7H1M6 2 1 7l5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          <span>Not what you meant?</span>
        </button>

        <div className="chosen-grid">
          <div className="chosen-copy">
            <div className="eyebrow">{eyebrow}</div>
            <h1 className="chosen-h1">{heading}</h1>
            <p className="chosen-lede">{copy}</p>

            {stats && (
              <div className="chosen-stats">
                {stats.map((s, i) => (
                  <div key={i}>
                    <div className="chosen-stat-num">{s.num}</div>
                    <div className="chosen-stat-label">{s.label}</div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div className="chosen-form">
            <ContactForm variant={variant} ctaCopy={ctaCopy} />
            {variant === "client" && <ReviewsWidget />}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Placeholder, useReveal, Arrow, Nav, Hero, ContactForm, ChosenPanel, HeroPrompt, ReviewsWidget });
