// Brief Us modal — category-qualified proposal flow
// Wired as the primary B2B conversion across the prototype.

const { useState: useStateB, useEffect: useEffectB } = React;

const SERVICE_OPTIONS = [
  { id: "sports",     title: "Sports & Motorsports",     desc: "Federations, leagues, rights holders" },
  { id: "festival",   title: "Festivals & Entertainment",desc: "Multi-day cultural / lifestyle" },
  { id: "activation", title: "Brand Activation",         desc: "Experiential, pop-ups, mall" },
  { id: "conference", title: "Conferences & Summits",    desc: "Stakeholder, B2B, policy" },
  { id: "ceremony",   title: "Ceremonies & Galas",       desc: "Awards, openings, gala dinners" },
  { id: "launch",    title: "Product Launch",            desc: "Reveals, press moments" },
];

const MARKETS = [
  { id: "uae",   title: "UAE",          desc: "Dubai · Abu Dhabi · Sharjah" },
  { id: "ksa",   title: "Saudi Arabia", desc: "Riyadh · Jeddah · AlUla · NEOM" },
  { id: "qatar", title: "Qatar",        desc: "Doha" },
  { id: "kuwait",title: "Kuwait",       desc: "" },
  { id: "intl", title: "International", desc: "Inbound / outbound GCC" },
  { id: "other", title: "Other / TBD",  desc: "Tell us where" },
];

const SCALES = [
  { id: "intimate", title: "Intimate", desc: "< 500 guests" },
  { id: "mid",      title: "Mid-scale",desc: "500–5,000" },
  { id: "large",    title: "Large",    desc: "5,000–50,000" },
  { id: "mega",     title: "Mega",     desc: "50,000+ / multi-city" },
];

const TIMELINES = [
  { id: "rush",  title: "< 3 months" },
  { id: "near",  title: "3–6 months" },
  { id: "mid",   title: "6–12 months" },
  { id: "long",  title: "12+ months / pitching" },
];

const STEPS = ["Service", "Scale & Market", "About you", "Brief"];

const BriefModal = ({ open, onClose, initialCategory }) => {
  const [step, setStep] = useStateB(0);
  const [data, setData] = useStateB({
    service: initialCategory || "",
    market: "",
    scale: "",
    timeline: "",
    name: "", company: "", role: "", email: "", phone: "",
    summary: "", attach: false,
  });
  const [done, setDone] = useStateB(false);

  useEffectB(() => {
    if (open) {
      setStep(0);
      setDone(false);
      setData(d => ({ ...d, service: initialCategory || d.service || "" }));
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open, initialCategory]);

  if (!open) return null;

  const set = (patch) => setData(d => ({ ...d, ...patch }));

  const canAdvance = (() => {
    if (step === 0) return !!data.service;
    if (step === 1) return !!data.market && !!data.scale;
    if (step === 2) return data.name && data.email && data.company;
    if (step === 3) return data.summary.length > 10;
    return false;
  })();

  const next = () => {
    if (step < STEPS.length - 1) setStep(s => s + 1);
    else setDone(true);
  };

  const stepLabel = STEPS[step];

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <aside className="modal__side">
          <button className="modal__close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
          </button>
          <div>
            <Kicker>Brief us / 0{step + 1} of 0{STEPS.length}</Kicker>
            <h3>Let's<br/>build it.</h3>
            <p>
              Tell us the category, market and scale. We'll route your brief to the right
              regional lead and reply within one working day.
            </p>
          </div>
          <div>
            <p style={{ fontSize: 12, color: "rgba(246,245,239,0.6)" }}>
              Or call directly:
            </p>
            <p style={{ margin: "4px 0 0", fontWeight: 600 }}>
              Dubai <a href="tel:+97143553444" style={{ color: "var(--accent)" }}>+971 4 355 3444</a><br/>
              Riyadh <a href="tel:+966114755546" style={{ color: "var(--accent)" }}>+966 11 475 5546</a>
            </p>
          </div>
        </aside>

        <div className="modal__body">
          {done ? <ThankYou data={data} onClose={onClose} /> : (
            <>
              <div className="modal__steps">
                {STEPS.map((s, i) => (
                  <div key={s} className={`modal__step ${i === step ? "is-active" : ""} ${i < step ? "is-done" : ""}`}>
                    <span className="num">{i < step ? <Check size={9}/> : i + 1}</span>
                    <span>{s}</span>
                  </div>
                ))}
              </div>

              {step === 0 && (
                <>
                  <h2 className="modal__h2">What are you producing?</h2>
                  <p className="modal__lead">Pick the closest category — we'll refine in the brief.</p>
                  <div className="option-grid">
                    {SERVICE_OPTIONS.map(o => (
                      <button key={o.id} className={`option ${data.service === o.id ? "is-selected" : ""}`} onClick={() => set({ service: o.id })}>
                        <span className="option__check">{data.service === o.id && <Check />}</span>
                        <span>
                          <div className="option__title">{o.title}</div>
                          <div className="option__desc">{o.desc}</div>
                        </span>
                      </button>
                    ))}
                  </div>
                </>
              )}

              {step === 1 && (
                <>
                  <h2 className="modal__h2">Where and how big?</h2>
                  <p className="modal__lead">So we route to Dubai HQ, Riyadh or Doha.</p>
                  <h4 style={{ marginTop: 4 }}>Primary market</h4>
                  <div className="option-grid option-grid--3" style={{ marginBottom: 24 }}>
                    {MARKETS.map(o => (
                      <button key={o.id} className={`option ${data.market === o.id ? "is-selected" : ""}`} onClick={() => set({ market: o.id })}>
                        <span className="option__check">{data.market === o.id && <Check />}</span>
                        <span>
                          <div className="option__title">{o.title}</div>
                          {o.desc && <div className="option__desc">{o.desc}</div>}
                        </span>
                      </button>
                    ))}
                  </div>
                  <h4>Scale</h4>
                  <div className="option-grid">
                    {SCALES.map(o => (
                      <button key={o.id} className={`option ${data.scale === o.id ? "is-selected" : ""}`} onClick={() => set({ scale: o.id })}>
                        <span className="option__check">{data.scale === o.id && <Check />}</span>
                        <span>
                          <div className="option__title">{o.title}</div>
                          <div className="option__desc">{o.desc}</div>
                        </span>
                      </button>
                    ))}
                  </div>
                </>
              )}

              {step === 2 && (
                <>
                  <h2 className="modal__h2">Who's briefing us?</h2>
                  <p className="modal__lead">We'll keep your details to procurement-grade standards.</p>
                  <div className="field-row">
                    <div className="field"><label>Name</label><input value={data.name} onChange={e => set({ name: e.target.value })} placeholder="Your full name" /></div>
                    <div className="field"><label>Role</label><input value={data.role} onChange={e => set({ role: e.target.value })} placeholder="Head of Events / Procurement" /></div>
                  </div>
                  <div className="field"><label>Company / Organisation</label><input value={data.company} onChange={e => set({ company: e.target.value })} placeholder="Organisation name" /></div>
                  <div className="field-row">
                    <div className="field"><label>Work email</label><input type="email" value={data.email} onChange={e => set({ email: e.target.value })} placeholder="name@company.com" /></div>
                    <div className="field"><label>Phone <span style={{ opacity: 0.5 }}>· optional</span></label><input value={data.phone} onChange={e => set({ phone: e.target.value })} placeholder="+971 …" /></div>
                  </div>
                </>
              )}

              {step === 3 && (
                <>
                  <h2 className="modal__h2">The brief</h2>
                  <p className="modal__lead">A few lines is plenty — we'll come back with questions.</p>
                  <div className="field"><label>Timeline</label>
                    <div className="option-grid option-grid--3" style={{ marginTop: 2 }}>
                      {TIMELINES.map(o => (
                        <button key={o.id} className={`option ${data.timeline === o.id ? "is-selected" : ""}`} onClick={() => set({ timeline: o.id })}>
                          <span className="option__check">{data.timeline === o.id && <Check />}</span>
                          <div className="option__title">{o.title}</div>
                        </button>
                      ))}
                    </div>
                  </div>
                  <div className="field"><label>Brief summary</label>
                    <textarea rows={5} value={data.summary} onChange={e => set({ summary: e.target.value })} placeholder="Event idea, audience, must-haves, anything we should know…" />
                  </div>
                  <label style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13, color: "var(--muted)", marginTop: 4 }}>
                    <input type="checkbox" checked={data.attach} onChange={e => set({ attach: e.target.checked })} />
                    I'll send a deck / RFP separately to <strong style={{ color: "var(--ink)" }}>proposals@blinkexperience.com</strong>
                  </label>
                </>
              )}

              <div className="modal__nav">
                <div className="modal__nav-left">
                  {step > 0 ? <button className="btn btn--outline-ink" onClick={() => setStep(s => s - 1)} style={{ padding: "10px 16px" }}>← Back</button> : <span>Step {step + 1} / {STEPS.length} · {stepLabel}</span>}
                </div>
                <button className={`btn btn--accent btn--lg ${!canAdvance ? "is-disabled" : ""}`}
                        disabled={!canAdvance}
                        style={{ opacity: canAdvance ? 1 : 0.4, cursor: canAdvance ? "pointer" : "not-allowed" }}
                        onClick={canAdvance ? next : null}>
                  {step === STEPS.length - 1 ? "Send brief" : "Continue"}
                  <ArrowRight />
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

const ThankYou = ({ data, onClose }) => (
  <div style={{ padding: "40px 0", textAlign: "left" }}>
    <BELoop />
    <h2 className="modal__h2" style={{ marginTop: 24, fontSize: 36 }}>Brief received.</h2>
    <p className="t-lead" style={{ color: "var(--muted)", marginBottom: 28, maxWidth: 480 }}>
      Thanks {data.name?.split(" ")[0] || "there"}. We'll come back from the {data.market?.toUpperCase() || "regional"} office within one working day.
    </p>
    <div style={{ background: "var(--paper-2)", padding: 20, borderRadius: 12, marginBottom: 24 }}>
      <table className="spec-table">
        <tbody>
          <tr><td>Reference</td><td style={{ fontFamily: "JetBrains Mono, monospace" }}>BE-2026-{Math.floor(Math.random() * 9000 + 1000)}</td></tr>
          <tr><td>Routed to</td><td>{data.market === "ksa" ? "Riyadh office" : data.market === "qatar" ? "Doha office" : "Dubai HQ"}</td></tr>
          <tr><td>Category</td><td>{SERVICE_OPTIONS.find(s => s.id === data.service)?.title || "—"}</td></tr>
          <tr><td>Scale</td><td>{SCALES.find(s => s.id === data.scale)?.title || "—"}</td></tr>
        </tbody>
      </table>
    </div>
    <button className="btn btn--ink btn--lg" onClick={onClose}>Close <ArrowRight /></button>
  </div>
);

Object.assign(window, { BriefModal });
