// ─── Planner Modal — "Talk to a planner" callback form
// Intent: callback-me lead, distinct from the wizard's quote-me lead.
// Tagged leadSource: "planner_callback" so the CRM can route appropriately.
//
// Open from anywhere:
//   window.dispatchEvent(new CustomEvent("openPlanner", {
//     detail: { source: "off-menu" | "wizard-budget" | "product:8m-dome",
//               venueInterest: "8m-dome",   // optional prefill
//               postcode: "SW1A 1AA",       // optional prefill
//               date: "2026-02-23",         // optional prefill (YYYY-MM-DD)
//               guests: 60,                  // optional prefill (number or string)
//               note: "..." }                // optional prefill
//   }))

const { useState: useP_S, useEffect: useP_E } = React;

function Planner() {
  const [open, setOpen] = useP_S(false);
  const [meta, setMeta] = useP_S({});
  const [sent, setSent] = useP_S(false);
  const [data, setData] = useP_S({
    name: "", phone: "", email: "", postcode: "",
    date: "", guests: "", venueInterest: "", notes: "",
  });
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  useP_E(() => {
    const onOpen = (e) => {
      const d = (e && e.detail) || {};
      setMeta(d);
      setData({
        name: "", phone: "", email: "",
        postcode: d.postcode || "",
        date: d.date || "",
        guests: d.guests != null ? String(d.guests) : "",
        venueInterest: d.venueInterest || "",
        notes: d.note || "",
      });
      setSent(false);
      setOpen(true);
    };
    window.addEventListener("openPlanner", onOpen);
    return () => window.removeEventListener("openPlanner", onOpen);
  }, []);

  if (!open) return null;
  const close = () => setOpen(false);

  const ready =
    data.name.trim().length > 1 &&
    data.phone.trim().length >= 7 &&
    /\S+@\S+\.\S+/.test(data.email) &&
    data.postcode.trim().length >= 3;

  const submit = () => {
    if (!ready) return;
    const payload = {
      leadSource: "planner_callback",
      capturedAt: new Date().toISOString(),
      source: meta.source || "direct",
      contact: {
        name: data.name.trim(),
        phone: data.phone.trim(),
        email: data.email.trim(),
        postcode: data.postcode.trim().toUpperCase(),
      },
      brief: {
        roughDate: data.date || null,
        roughGuests: data.guests || null,
        venueInterest: data.venueInterest || null,
        notes: data.notes.trim() || null,
      },
    };
    try { console.info("[planner] lead captured", payload); } catch (e) {}
    try {
      const queue = JSON.parse(localStorage.getItem("pp_planner_queue") || "[]");
      queue.push(payload);
      localStorage.setItem("pp_planner_queue", JSON.stringify(queue));
    } catch (e) {}
    setSent(true);
  };

  const venueOpts = (window.PP_CATALOG && window.PP_CATALOG.venues) || [];

  return (
    <div className="modal-shroud open" onClick={close}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{maxWidth: 720}}>
        <div className="modal-head">
          <div>
            <div className="label">Talk to a planner</div>
            <div style={{fontFamily:"var(--font-display)",fontWeight:700,fontSize:18,letterSpacing:"-0.01em",marginTop:2}}>
              We'll call you back. No pressure quote.
            </div>
          </div>
          <button onClick={close} aria-label="Close" style={{width:36,height:36,borderRadius:"50%",background:"var(--surface-2)",border:"1px solid var(--line)",display:"flex",alignItems:"center",justifyContent:"center"}}>
            <Icon.X width={18} height={18}/>
          </button>
        </div>

        {sent ? (
          <div className="modal-body" style={{textAlign:"center",padding:"60px 36px"}}>
            <div style={{width:88,height:88,borderRadius:"50%",background:"var(--grad-pink)",boxShadow:"0 20px 60px rgba(255,46,138,0.5)",display:"inline-flex",alignItems:"center",justifyContent:"center",marginBottom:24}}>
              <Icon.Check width={42} height={42} style={{color:"#fff"}}/>
            </div>
            <h2>We've got it. <span className="txt-gold">Callback within 2 hours.</span></h2>
            <p style={{color:"var(--ink-2)",fontSize:15.5,lineHeight:1.55,maxWidth:480,margin:"8px auto 24px"}}>
              A planner will call <strong style={{color:"var(--ink-0)"}}>{data.phone}</strong> to talk through your party and your budget — we'll build a quote that fits.
            </p>
            <button className="btn btn-ghost" onClick={close}>Back to site</button>
          </div>
        ) : (
          <>
            <div className="modal-body">
              <h2>Let's <span className="txt-pink">plan it together.</span></h2>
              <p className="lede">Got a budget in mind? We'll build a night that fits it. Tell us how to reach you and a planner will call back within 2 hours.</p>

              <div style={{display:"grid",gap:14}}>
                <div className="field-row">
                  <div className="field">
                    <label>Your name <span style={{color:"var(--pink-glow)"}}>*</span></label>
                    <input placeholder="Jamie Smith" value={data.name} onChange={e => set("name", e.target.value)}/>
                  </div>
                  <div className="field">
                    <label>Phone <span style={{color:"var(--pink-glow)"}}>*</span></label>
                    <input type="tel" placeholder="07700 900000" value={data.phone} onChange={e => set("phone", e.target.value)}/>
                  </div>
                </div>
                <div className="field-row">
                  <div className="field">
                    <label>Email <span style={{color:"var(--pink-glow)"}}>*</span></label>
                    <input type="email" placeholder="jamie@example.com" value={data.email} onChange={e => set("email", e.target.value)}/>
                  </div>
                  <div className="field">
                    <label>Postcode <span style={{color:"var(--pink-glow)"}}>*</span></label>
                    <input placeholder="CM15 8BA" value={data.postcode} onChange={e => set("postcode", e.target.value.toUpperCase())}/>
                  </div>
                </div>

                <div style={{margin:"6px 0 -2px",fontFamily:"var(--font-mono)",fontSize:11,color:"var(--ink-3)",letterSpacing:"0.08em",textTransform:"uppercase"}}>
                  Optional — helps us prep
                </div>

                <div className="field-row">
                  <div className="field">
                    <label>Rough date <span style={{color:"var(--ink-3)",fontWeight:400}}>(or "not sure")</span></label>
                    <input type="text" placeholder="e.g. Sat 14 June, or 'not sure yet'" value={data.date} onChange={e => set("date", e.target.value)}/>
                  </div>
                  <div className="field">
                    <label>Rough guest count</label>
                    <input type="text" placeholder="e.g. 40, or 'TBD'" value={data.guests} onChange={e => set("guests", e.target.value)}/>
                  </div>
                </div>

                <div className="field">
                  <label>Venue you've got in mind</label>
                  <select value={data.venueInterest} onChange={e => set("venueInterest", e.target.value)}>
                    <option value="">Not sure yet — happy to be guided</option>
                    {venueOpts.map(v => (
                      <option key={v.id} value={v.id}>{v.name} · up to {v.capacity} guests · from £{v.price}</option>
                    ))}
                  </select>
                </div>

                <div className="field">
                  <label>Anything we should know? <span style={{color:"var(--ink-3)",fontWeight:400}}>(budget, vibe, must-haves)</span></label>
                  <textarea rows="3" placeholder="e.g. budget around £1,200, want lasers and a DJ booth, mid-week if possible"
                            value={data.notes} onChange={e => set("notes", e.target.value)} />
                </div>
              </div>

              <div style={{marginTop:18, padding:14, borderRadius:"var(--r-md)", background:"var(--surface)", border:"1px solid var(--line)", display:"flex",gap:12,alignItems:"flex-start",fontSize:13,color:"var(--ink-2)"}}>
                <span style={{fontSize:18}}>🤝</span>
                <span>Planners call from a UK landline within working hours (9–6, Mon–Sat). We'll work within whatever budget you've got — no pressure, no upsell.</span>
              </div>
            </div>
            <div className="modal-foot">
              <button className="btn btn-ghost btn-sm" onClick={close}>
                <Icon.Back/> Cancel
              </button>
              <button className="btn btn-primary btn-sm"
                      disabled={!ready}
                      style={{opacity: ready ? 1 : 0.4}}
                      onClick={submit}>
                Request callback <Icon.Arrow/>
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// Expose globally so it can be mounted from any page-level App.
Object.assign(window, { Planner });
