// Brief — a 4-step client intake questionnaire.
// Walks a prospective client through the questions Gency needs answered
// to scope a logo / identity / illustration project properly.
//
// Lives on its own route (/brief). Linked from the Contact page CTA and the nav.

function BriefPage({ navigate }) {
  const STEPS = ["You", "Business", "Project", "Direction"];
  const BRIEF_EMAIL = "hello@gencydesigns.com";

  const WEB3FORMS_KEY = "11732c5c-0dea-412b-bb75-933b03e14d5a";

  const [step, setStep] = useState(0);
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState(false);
  const [mailHref, setMailHref] = useState("#");
  const [errors, setErrors] = useState({});

  const [brief, setBrief] = useState({
    // Step 1 — You
    name: "", role: "", email: "",
    company: "", website: "",
    // Step 2 — Business
    sector: "", stage: "Established 1–3 years",
    proposition: "", audience: "", competitors: "",
    // Step 3 — Project
    services: [],         // multi-select
    haveBrand: "No, starting fresh",
    deliverables: [],     // multi-select — where the mark needs to live
    nameStatus: "Yes — name is locked",
    // Step 4 — Direction
    moodWords: "", references: "", avoids: "",
    budget: "By quote",
    timeline: "2–3 weeks",
    decisionMakers: "", extra: "",
  });

  const update = (k, v) => setBrief(b => ({ ...b, [k]: v }));
  const toggle = (k, v) => setBrief(b => ({
    ...b,
    [k]: b[k].includes(v) ? b[k].filter(x => x !== v) : [...b[k], v],
  }));

  // Per-step validation
  const validateStep = (s) => {
    const e = {};
    if (s === 0) {
      if (!brief.name.trim()) e.name = "Required";
      if (!brief.email.trim()) e.email = "Required";
      else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(brief.email)) e.email = "Check this";
      if (!brief.company.trim()) e.company = "Required";
    } else if (s === 1) {
      if (!brief.sector.trim()) e.sector = "Required";
      if (!brief.proposition.trim() || brief.proposition.length < 20) e.proposition = "A sentence or two, please";
      if (!brief.audience.trim() || brief.audience.length < 15) e.audience = "Tell me who they are";
    } else if (s === 2) {
      if (brief.services.length === 0) e.services = "Pick at least one";
    } else if (s === 3) {
      if (!brief.moodWords.trim()) e.moodWords = "A few words, please";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (validateStep(step)) {
      setStep(s => Math.min(s + 1, STEPS.length - 1));
      window.scrollTo({ top: 240, behavior: "smooth" });
    }
  };
  const back = () => {
    setErrors({});
    setStep(s => Math.max(s - 1, 0));
    window.scrollTo({ top: 240, behavior: "smooth" });
  };
  // Compose a pre-filled email addressed to the studio so the submission
  // actually lands in the inbox (no backend required). Opens the visitor's
  // mail client with every answer laid out in the body.
  const buildMailHref = () => {
    const b = brief;
    const line = (k, v) => `${k}: ${v && String(v).trim() ? v : "\u2014"}`;
    const body = [
      `New project brief from ${b.name || "a visitor"}`,
      `Submitted ${new Date().toLocaleString()}`,
      ``,
      `\u2500\u2500 YOU \u2500\u2500`,
      line("Name", b.name),
      line("Role", b.role),
      line("Email", b.email),
      line("Company", b.company),
      line("Website / social", b.website),
      ``,
      `\u2500\u2500 BUSINESS \u2500\u2500`,
      line("Sector", b.sector),
      line("Stage", b.stage),
      line("What the company does", b.proposition),
      line("Audience", b.audience),
      line("Competitors", b.competitors),
      ``,
      `\u2500\u2500 PROJECT \u2500\u2500`,
      line("Needs", b.services.join(", ")),
      line("Where the mark lives", b.deliverables.join(", ")),
      line("Existing assets", b.haveBrand),
      line("Name status", b.nameStatus),
      ``,
      `\u2500\u2500 DIRECTION \u2500\u2500`,
      line("Mood words", b.moodWords),
      line("References", b.references),
      line("Avoids", b.avoids),
      line("Budget", b.budget),
      line("Timeline", b.timeline),
      line("Decision-makers", b.decisionMakers),
      line("Anything else", b.extra),
    ].join("\n");
    const subject = `Project brief \u2014 ${b.company || b.name || "New enquiry"}`;
    return `mailto:${BRIEF_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  };

  // Build a flat, readable payload for Web3Forms.
  const buildPayload = () => {
    const b = brief;
    return {
      access_key: WEB3FORMS_KEY,
      subject: `Project brief \u2014 ${b.company || b.name || "New enquiry"}`,
      from_name: b.name || "Website visitor",
      replyto: b.email || "",
      // — You —
      Name: b.name, Role: b.role, Email: b.email,
      Company: b.company, "Website / social": b.website,
      // — Business —
      Sector: b.sector, Stage: b.stage,
      "What the company does": b.proposition,
      Audience: b.audience, Competitors: b.competitors,
      // — Project —
      Needs: b.services.join(", "),
      "Where the mark lives": b.deliverables.join(", "),
      "Existing assets": b.haveBrand, "Name status": b.nameStatus,
      // — Direction —
      "Mood words": b.moodWords, References: b.references, Avoids: b.avoids,
      Budget: b.budget, Timeline: b.timeline,
      "Decision-makers": b.decisionMakers, "Anything else": b.extra,
    };
  };

  const submit = async () => {
    if (!validateStep(step)) return;
    // Keep a mailto ready as a manual fallback.
    const href = buildMailHref();
    setMailHref(href);
    setSending(true);
    setSendError(false);
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify(buildPayload()),
      });
      const out = await res.json().catch(() => ({}));
      if (res.ok && out.success) {
        setSubmitted(true);
      } else {
        setSendError(true);
      }
    } catch (err) {
      // Network blocked / offline — fall back to the visitor's mail client.
      setSendError(true);
    } finally {
      setSending(false);
    }
  };

  // ───── CONFIRMATION ─────
  if (submitted) {
    return (
      <main style={{ background: "var(--black)", minHeight: "100vh", display: "flex", alignItems: "center" }}>
        <section className="wrap-narrow" style={{ padding: "200px 40px", textAlign: "center" }}>
          <div className="mono" style={{ color: "var(--red)", marginBottom: 28 }}>
            ▸ BRIEF RECEIVED · {new Date().toLocaleDateString()}
          </div>
          <h1 className="display" style={{ fontSize: "clamp(48px, 8vw, 120px)", letterSpacing: "-0.005em" }}>
            Thank you,<br/><span style={{ color: "var(--red)" }}>{brief.name.split(" ")[0]}.</span>
          </h1>
          <p className="lead" style={{ marginTop: 32, marginInline: "auto" }}>
            Your brief landed safely in my inbox — sent to <span style={{ color: "var(--white)", borderBottom: "1px solid var(--red)" }}>{BRIEF_EMAIL}</span>. Nothing else to do. I reply within 12 hours, usually with two or three follow-up questions and a proposed scope.
          </p>
          <div style={{ marginTop: 44, display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
            <button onClick={() => navigate("portfolio")} className="btn btn-red">See more work</button>
            <button onClick={() => navigate("home")} className="btn btn-ghost">Back home</button>
          </div>
        </section>
      </main>
    );
  }

  // ───── MAIN ─────
  return (
    <main>
      <PageHeader
        index="04"
        label="Brief · Project intake"
        title={<>The full<br/>brief.</>}
        sub="Twelve questions that tell me what your moodboard can't. Most clients finish it in eight minutes. Replies within 12 hours, 7/7."
        ghost="BRIEF"
      />

      <section className="pad">
        <div className="wrap" style={{ maxWidth: 980 }}>
          {/* Progress bar */}
          <Reveal>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16, flexWrap: "wrap", gap: 12 }}>
              <span className="mono" style={{ color: "var(--red)" }}>
                STEP {String(step + 1).padStart(2, "0")} / {String(STEPS.length).padStart(2, "0")} — {STEPS[step].toUpperCase()}
              </span>
              <span className="mono gray">~{8 - step * 2} min remaining</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: `repeat(${STEPS.length}, 1fr)`, gap: 8, marginBottom: 64 }}>
              {STEPS.map((_, i) => (
                <div key={i} style={{
                  height: 2,
                  background: i <= step ? "var(--red)" : "var(--line)",
                  transition: "background .4s ease",
                }} />
              ))}
            </div>
          </Reveal>

          {/* Step content */}
          {step === 0 && (
            <Reveal key="step0">
              <h2 className="display" style={{ fontSize: "clamp(36px, 4.6vw, 64px)", marginBottom: 36, letterSpacing: "-0.005em" }}>
                First, <span style={{ color: "var(--red)" }}>who's writing.</span>
              </h2>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 36, marginBottom: 32 }}>
                <BriefField label="/ 01 — Your full name" error={errors.name}>
                  <input type="text" value={brief.name} onChange={e => update("name", e.target.value)} placeholder="Elena Marsh" autoComplete="name" />
                </BriefField>
                <BriefField label="/ 02 — Your role" error={errors.role}>
                  <input type="text" value={brief.role} onChange={e => update("role", e.target.value)} placeholder="Founder · Creative Director · Marketing Lead" />
                </BriefField>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 36, marginBottom: 32 }}>
                <BriefField label="/ 03 — Email" error={errors.email}>
                  <input type="email" value={brief.email} onChange={e => update("email", e.target.value)} placeholder="elena@northfolk.co" autoComplete="email" />
                </BriefField>
                <BriefField label="/ 04 — Company name" error={errors.company}>
                  <input type="text" value={brief.company} onChange={e => update("company", e.target.value)} placeholder="North/Folk Coffee Co." />
                </BriefField>
              </div>
              <BriefField label="/ 05 — Website or social (if any)">
                <input type="text" value={brief.website} onChange={e => update("website", e.target.value)} placeholder="northfolk.co · @northfolk" />
              </BriefField>
            </Reveal>
          )}

          {step === 1 && (
            <Reveal key="step1">
              <h2 className="display" style={{ fontSize: "clamp(36px, 4.6vw, 64px)", marginBottom: 36, letterSpacing: "-0.005em" }}>
                Tell me about<br/><span style={{ color: "var(--red)" }}>the business.</span>
              </h2>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 36, marginBottom: 32 }}>
                <BriefField label="/ 06 — Sector / industry" error={errors.sector}>
                  <input type="text" value={brief.sector} onChange={e => update("sector", e.target.value)} placeholder="Specialty coffee · Hospitality · SaaS · Publishing" />
                </BriefField>
                <BriefField label="/ 07 — Where are you at?" error={errors.stage}>
                  <select value={brief.stage} onChange={e => update("stage", e.target.value)}>
                    <option>Pre-launch (still building)</option>
                    <option>Just launched (under 1 year)</option>
                    <option>Established 1–3 years</option>
                    <option>Mature (3+ years, refreshing)</option>
                    <option>Pivot or rebrand</option>
                  </select>
                </BriefField>
              </div>
              <BriefField label="/ 08 — In a sentence, what does the company do?" error={errors.proposition}>
                <textarea rows="3" value={brief.proposition} onChange={e => update("proposition", e.target.value)} placeholder="We roast specialty coffee in small batches and sell it through two cafés and a subscription service in the Pacific Northwest." />
              </BriefField>
              <BriefField label="/ 09 — Who is it for? Describe your ideal customer." error={errors.audience}>
                <textarea rows="3" value={brief.audience} onChange={e => update("audience", e.target.value)} placeholder="Quiet coffee enthusiasts in their 30s — they bought their first manual brewer in lockdown and now read About sections. Notice typography. Travel for restaurants." />
              </BriefField>
              <BriefField label="/ 10 — Three competitors or peers (helpful to position against)" hint="Names will do. Links if you have them.">
                <textarea rows="2" value={brief.competitors} onChange={e => update("competitors", e.target.value)} placeholder="Onyx · Sey Coffee · Tim Wendelboe" />
              </BriefField>
            </Reveal>
          )}

          {step === 2 && (
            <Reveal key="step2">
              <h2 className="display" style={{ fontSize: "clamp(36px, 4.6vw, 64px)", marginBottom: 36, letterSpacing: "-0.005em" }}>
                Now the<br/><span style={{ color: "var(--red)" }}>project itself.</span>
              </h2>

              <BriefField label="/ 11 — What do you actually need? Pick all that apply." error={errors.services}>
                <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 8 }}>
                  {[
                    "Logo / wordmark",
                    "Full brand identity",
                    "Identity refresh",
                    "Illustration",
                    "Packaging",
                    "Art direction",
                    "Type / lettering",
                    "Not sure yet",
                  ].map(s => (
                    <button type="button" key={s}
                      onClick={() => toggle("services", s)}
                      className={"tag" + (brief.services.includes(s) ? " active" : "")}
                      style={{ cursor: "pointer" }}>
                      {s}
                    </button>
                  ))}
                </div>
              </BriefField>

              <BriefField label="/ 12 — Where does the mark need to live? Pick all that apply.">
                <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 8 }}>
                  {[
                    "Website",
                    "Mobile / app icon",
                    "Packaging",
                    "Apparel",
                    "Print / editorial",
                    "Signage",
                    "Social",
                    "Embroidery / woven label",
                    "Vehicle / wrap",
                  ].map(s => (
                    <button type="button" key={s}
                      onClick={() => toggle("deliverables", s)}
                      className={"tag" + (brief.deliverables.includes(s) ? " active" : "")}
                      style={{ cursor: "pointer" }}>
                      {s}
                    </button>
                  ))}
                </div>
              </BriefField>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 36, marginBottom: 32 }}>
                <BriefField label="/ 13 — Do you have existing brand assets?">
                  <select value={brief.haveBrand} onChange={e => update("haveBrand", e.target.value)}>
                    <option>No, starting fresh</option>
                    <option>Yes, but I want a full refresh</option>
                    <option>Yes — only the logo needs work</option>
                    <option>Yes — only the system around it needs work</option>
                    <option>Some elements done by someone else</option>
                  </select>
                </BriefField>
                <BriefField label="/ 14 — Is the company name decided?">
                  <select value={brief.nameStatus} onChange={e => update("nameStatus", e.target.value)}>
                    <option>Yes — name is locked</option>
                    <option>Name is locked but I want feedback</option>
                    <option>Choosing between 2–3 options</option>
                    <option>No — naming is part of this project</option>
                  </select>
                </BriefField>
              </div>
            </Reveal>
          )}

          {step === 3 && (
            <Reveal key="step3">
              <h2 className="display" style={{ fontSize: "clamp(36px, 4.6vw, 64px)", marginBottom: 36, letterSpacing: "-0.005em" }}>
                Finally,<br/><span style={{ color: "var(--red)" }}>the feel.</span>
              </h2>

              <BriefField label="/ 15 — Five adjectives that describe how the brand should feel" hint="Don't overthink. Honest words beat clever ones." error={errors.moodWords}>
                <textarea rows="2" value={brief.moodWords} onChange={e => update("moodWords", e.target.value)} placeholder="Quiet · Confident · Hand-made · Generous · Grown-up" />
              </BriefField>

              <BriefField label="/ 16 — Brands, websites or images you admire" hint="From any sector. Links or names. The opposite of yours is just as useful.">
                <textarea rows="3" value={brief.references} onChange={e => update("references", e.target.value)} placeholder="Aesop · Cajva.com · Heretic Studio · the back cover of the New Yorker" />
              </BriefField>

              <BriefField label="/ 17 — Anything you definitely don't want">
                <textarea rows="2" value={brief.avoids} onChange={e => update("avoids", e.target.value)} placeholder="No gradients · no 'modern' geometric sans · no mascot" />
              </BriefField>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 36, marginBottom: 32 }}>
                <BriefField label="/ 18 — Budget approach">
                  <select value={brief.budget} onChange={e => update("budget", e.target.value)}>
                    <option>By quote</option>
                    <option>Modest · lean</option>
                    <option>Mid · standard</option>
                    <option>Generous · ambitious</option>
                    <option>Let's discuss</option>
                  </select>
                </BriefField>
                <BriefField label="/ 19 — Timeline">
                  <select value={brief.timeline} onChange={e => update("timeline", e.target.value)}>
                    <option>1 week</option>
                    <option>2–3 weeks</option>
                    <option>3–4 weeks</option>
                    <option>4+ weeks (flexible)</option>
                    <option>Just exploring</option>
                  </select>
                </BriefField>
              </div>

              <BriefField label="/ 20 — Who signs off? Decision-makers on your side." hint="Just titles — Founder, CMO, Board. Tells me how to scope reviews.">
                <input type="text" value={brief.decisionMakers} onChange={e => update("decisionMakers", e.target.value)} placeholder="Founder + Head of Marketing" />
              </BriefField>

              <BriefField label="/ 21 — Anything else worth knowing?" hint="A story, a constraint, a deadline, a hope. Even one sentence helps.">
                <textarea rows="3" value={brief.extra} onChange={e => update("extra", e.target.value)} placeholder="Optional." />
              </BriefField>
            </Reveal>
          )}

          {/* Footer controls */}
          <div style={{ marginTop: 48, paddingTop: 24, borderTop: "1px solid var(--line)",
            display: "flex", justifyContent: "space-between", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
            <button onClick={back} disabled={step === 0} className="btn btn-ghost"
              style={{ opacity: step === 0 ? 0.35 : 1, pointerEvents: step === 0 ? "none" : "auto" }}>
              ← Back
            </button>

            <p className="mono gray" style={{ fontSize: 11, maxWidth: 360, textAlign: "center" }}>
              Your answers stay with me. No CRM, no third parties.
            </p>

            {step < STEPS.length - 1 ? (
              <button onClick={next} className="btn btn-red">Continue →</button>
            ) : (
              <button onClick={submit} disabled={sending} className="btn btn-red" style={{ opacity: sending ? 0.6 : 1, pointerEvents: sending ? "none" : "auto" }}>
                {sending ? "Sending\u2026" : "Send the brief →"}
              </button>
            )}
          </div>

          {/* Send failure — offer the mailto fallback */}
          {sendError && (
            <div style={{ marginTop: 22, textAlign: "center" }}>
              <p className="mono" style={{ color: "var(--red)", fontSize: 12, marginBottom: 10 }}>
                Couldn't send automatically. Use your email app instead:
              </p>
              <a href={mailHref} className="btn btn-ghost">Send the brief by email →</a>
            </div>
          )}

          {/* Quick exit */}
          <div style={{ marginTop: 40, textAlign: "center" }}>
            <button onClick={() => navigate("contact")} className="mono gray" style={{ textDecoration: "underline" }}>
              Or send a short note instead →
            </button>
          </div>
        </div>
      </section>
    </main>
  );
}

// Small field wrapper used by BriefPage.
function BriefField({ label, hint, error, children }) {
  return (
    <div className={"field" + (error ? " err" : "")} style={{ marginBottom: error || hint ? 32 : 32 }}>
      <label>{label}</label>
      {children}
      {hint && !error && <span className="mono gray" style={{ fontSize: 10, letterSpacing: ".14em" }}>{hint.toUpperCase()}</span>}
      {error && <span className="err-msg">{error}</span>}
    </div>
  );
}

Object.assign(window, { BriefPage });
