// =============================================================
// Design Brains — Multi-step Quotation Form
// =============================================================

const QUOTE_STEPS = [
  { key: "service", label: "Service" },
  { key: "type", label: "Project Type" },
  { key: "features", label: "Features" },
  { key: "budget", label: "Budget" },
  { key: "timeline", label: "Timeline" },
  { key: "contact", label: "Contact" },
  { key: "review", label: "Review" },
];

function QuotePage() {
  const { route } = useRouter();
  const initialService = useMemo(() => {
    const m = route.match(/\/quote\/?(.*)?/);
    if (m && m[1]) return m[1];
    return "";
  }, []);

  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    service: initialService || "",
    type: "",
    features: [],
    budget: "",
    timeline: "",
    name: "",
    email: "",
    company: "",
    phone: "",
    message: "",
    fileName: "",
  });
  const [submitted, setSubmitted] = useState(false);
  const [errors, setErrors] = useState({});

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

  const validateStep = () => {
    const e = {};
    if (step === 0 && !data.service) e.service = "Pick a service";
    if (step === 1 && !data.type) e.type = "Pick a project type";
    if (step === 3 && !data.budget) e.budget = "Pick a budget range";
    if (step === 4 && !data.timeline) e.timeline = "Pick a timeline";
    if (step === 5) {
      if (!data.name) e.name = "Required";
      if (!data.email || !/.+@.+\..+/.test(data.email)) e.email = "Valid email required";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (!validateStep()) return;
    setStep((s) => Math.min(s + 1, QUOTE_STEPS.length - 1));
  };
  const back = () => setStep((s) => Math.max(s - 1, 0));

  if (submitted) return <QuoteSuccess data={data} />;

  return (
    <div className="page-enter">
      <PageHero
        eyebrow="Quote · 24-hour reply"
        title={<>Tell us about your <span style={{ color: "var(--brand)" }}>project</span>.</>}
        subtitle="Seven quick questions. Most teams finish in under three minutes — we'll come back within 24 hours with a clear plan and rough cost."
      />

      <section style={{ paddingTop: 20 }}>
        <div className="container" style={{ maxWidth: 880 }}>
          {/* Progress */}
          <div style={{ marginBottom: 48 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
              <div className="font-mono" style={{ fontSize: 12, color: "var(--brand)", letterSpacing: "0.16em" }}>
                STEP {String(step + 1).padStart(2, "0")} / {String(QUOTE_STEPS.length).padStart(2, "0")}
              </div>
              <div className="font-mono" style={{ fontSize: 12, color: "var(--muted)", letterSpacing: "0.12em", textTransform: "uppercase" }}>
                {QUOTE_STEPS[step].label}
              </div>
            </div>
            <div style={{ height: 4, background: "var(--border)", borderRadius: 99, overflow: "hidden", position: "relative" }}>
              <div style={{
                position: "absolute", left: 0, top: 0, bottom: 0,
                width: `${((step + 1) / QUOTE_STEPS.length) * 100}%`,
                background: "var(--brand)",
                boxShadow: "0 0 12px var(--brand-glow)",
                transition: "width 0.5s var(--ease)",
              }}/>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 14, gap: 4 }} className="step-labels">
              {QUOTE_STEPS.map((s, i) => (
                <div key={s.key} style={{
                  fontSize: 11, fontFamily: "JetBrains Mono, monospace", letterSpacing: "0.05em",
                  color: i === step ? "var(--brand)" : i < step ? "var(--fg-2)" : "var(--muted-2)",
                  textTransform: "uppercase",
                  transition: "color 0.3s var(--ease)",
                }}>{s.label}</div>
              ))}
            </div>
          </div>

          {/* Step body */}
          <div className="card" style={{ padding: "clamp(28px, 4vw, 48px)", minHeight: 420 }}>
            <div key={step} className="page-enter">
              {step === 0 && <StepService data={data} update={update} error={errors.service} />}
              {step === 1 && <StepType data={data} update={update} error={errors.type} />}
              {step === 2 && <StepFeatures data={data} toggle={toggle} />}
              {step === 3 && <StepBudget data={data} update={update} error={errors.budget} />}
              {step === 4 && <StepTimeline data={data} update={update} error={errors.timeline} />}
              {step === 5 && <StepContact data={data} update={update} errors={errors} />}
              {step === 6 && <StepReview data={data} setStep={setStep} />}
            </div>
          </div>

          {/* Nav */}
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24, gap: 12, flexWrap: "wrap" }}>
            <button
              className="btn btn-ghost"
              onClick={back}
              disabled={step === 0}
              style={{ opacity: step === 0 ? 0.4 : 1, cursor: step === 0 ? "not-allowed" : "pointer" }}
            >
              ← Back
            </button>
            {step < QUOTE_STEPS.length - 1 ? (
              <button className="btn btn-primary" onClick={next}>
                Continue <span className="arrow">→</span>
              </button>
            ) : (
              <button className="btn btn-primary" onClick={() => setSubmitted(true)}>
                Submit request <span className="arrow">→</span>
              </button>
            )}
          </div>
        </div>
        <style>{`
          @media (max-width: 720px) {
            .step-labels > div { display: none; }
            .step-labels > div:nth-child(1), .step-labels > div:nth-child(${QUOTE_STEPS.length}) { display: block !important; }
          }
        `}</style>
      </section>
    </div>
  );
}

function StepService({ data, update, error }) {
  const opts = [
    { key: "web", title: "Website Development", desc: "Marketing sites, e-commerce, web apps", icon: "web" },
    { key: "app", title: "App Development", desc: "iOS, Android, cross-platform", icon: "app" },
    { key: "ai", title: "AI Automation", desc: "Chatbots, workflow, integrations", icon: "ai" },
    { key: "multiple", title: "Multiple / not sure yet", desc: "We'll help you scope it on the call", icon: "web" },
  ];
  return (
    <div>
      <h2 className="font-display" style={{ fontSize: 28, marginBottom: 8 }}>What kind of work?</h2>
      <p style={{ color: "var(--muted)", marginBottom: 28 }}>Pick the closest fit — we'll dig into the details on the call.</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="opts-grid">
        {opts.map((o) => {
          const sel = data.service === o.key;
          return (
            <button
              key={o.key}
              onClick={() => update("service", o.key)}
              style={{
                background: sel ? "var(--brand-faint)" : "rgba(255,255,255,0.02)",
                border: `1px solid ${sel ? "var(--brand)" : "var(--border)"}`,
                borderRadius: 14,
                padding: 20,
                textAlign: "left",
                cursor: "pointer",
                display: "flex",
                gap: 16,
                alignItems: "flex-start",
                transition: "all 0.2s var(--ease)",
                color: "var(--fg)",
              }}
            >
              <div style={{ flexShrink: 0 }}>
                <ServiceIcon kind={o.icon} size={36} />
              </div>
              <div>
                <div style={{ fontFamily: "DM Sans", fontSize: 18, fontWeight: 600, marginBottom: 4 }}>{o.title}</div>
                <div style={{ color: "var(--muted)", fontSize: 13 }}>{o.desc}</div>
              </div>
            </button>
          );
        })}
      </div>
      {error && <div style={{ color: "var(--danger)", fontSize: 13, marginTop: 16 }}>{error}</div>}
      <style>{`@media (max-width: 600px) { .opts-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

function StepType({ data, update, error }) {
  const map = {
    web: ["New marketing site", "E-commerce store", "Web app / SaaS", "Landing page", "Site redesign", "Other"],
    app: ["iOS app", "Android app", "Cross-platform", "Internal tool", "Existing app rework", "Other"],
    ai: ["Chatbot", "Workflow automation", "CRM automation", "Document / RAG system", "AI feature in existing product", "Other"],
    multiple: ["Brand + website", "Web + mobile app", "Product + automation", "Full digital transformation", "Other"],
    "": ["Pick a service first"],
  };
  const opts = map[data.service] || [];
  return (
    <div>
      <h2 className="font-display" style={{ fontSize: 28, marginBottom: 8 }}>What type of project?</h2>
      <p style={{ color: "var(--muted)", marginBottom: 28 }}>Closest match is fine — we'll refine in conversation.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {opts.map((o) => {
          const sel = data.type === o;
          return (
            <button
              key={o}
              onClick={() => update("type", o)}
              style={{
                background: sel ? "var(--brand-faint)" : "rgba(255,255,255,0.02)",
                border: `1px solid ${sel ? "var(--brand)" : "var(--border)"}`,
                borderRadius: 12,
                padding: "16px 20px",
                textAlign: "left",
                cursor: "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                gap: 16,
                color: "var(--fg)",
                fontSize: 15, fontWeight: 500,
                transition: "all 0.2s var(--ease)",
              }}
            >
              {o}
              <div style={{
                width: 22, height: 22, borderRadius: "50%",
                border: `1.5px solid ${sel ? "var(--brand)" : "var(--border-strong)"}`,
                display: "grid", placeItems: "center",
                background: sel ? "var(--brand)" : "transparent",
              }}>
                {sel && <svg width="10" height="10" viewBox="0 0 10 10"><path d="M2 5L4 7L8 3" stroke="#0A0C09" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none"/></svg>}
              </div>
            </button>
          );
        })}
      </div>
      {error && <div style={{ color: "var(--danger)", fontSize: 13, marginTop: 16 }}>{error}</div>}
    </div>
  );
}

function StepFeatures({ data, toggle }) {
  const feats = [
    "User authentication", "Payments / subscriptions", "Multi-language", "CMS / blog",
    "Search", "Analytics dashboard", "Admin panel", "Notifications",
    "Third-party integrations", "API / developer access", "AI features", "Real-time updates",
  ];
  return (
    <div>
      <h2 className="font-display" style={{ fontSize: 28, marginBottom: 8 }}>Features needed?</h2>
      <p style={{ color: "var(--muted)", marginBottom: 28 }}>Pick anything relevant. Skip if you're unsure — we'll workshop it together.</p>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
        {feats.map((f) => {
          const sel = data.features.includes(f);
          return (
            <button
              key={f}
              onClick={() => toggle("features", f)}
              style={{
                background: sel ? "var(--brand)" : "rgba(255,255,255,0.03)",
                border: `1px solid ${sel ? "var(--brand)" : "var(--border)"}`,
                color: sel ? "#0A0C09" : "var(--fg-2)",
                borderRadius: 999,
                padding: "10px 18px",
                fontSize: 14, fontWeight: 500,
                cursor: "pointer",
                transition: "all 0.2s var(--ease)",
              }}
            >
              {sel && "✓ "}{f}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function StepBudget({ data, update, error }) {
  const opts = [
    { v: "< $5k", d: "Landing page or simple site" },
    { v: "$5k – $15k", d: "Marketing site, small app" },
    { v: "$15k – $40k", d: "Most projects land here" },
    { v: "$40k – $100k", d: "Web app or mobile app" },
    { v: "$100k+", d: "Multi-month engagement" },
    { v: "Not sure", d: "We'll suggest a range" },
  ];
  return (
    <div>
      <h2 className="font-display" style={{ fontSize: 28, marginBottom: 8 }}>Budget range?</h2>
      <p style={{ color: "var(--muted)", marginBottom: 28 }}>Helps us scope right. We'll always come back with options.</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }} className="opts-grid">
        {opts.map((o) => {
          const sel = data.budget === o.v;
          return (
            <button
              key={o.v}
              onClick={() => update("budget", o.v)}
              style={{
                background: sel ? "var(--brand-faint)" : "rgba(255,255,255,0.02)",
                border: `1px solid ${sel ? "var(--brand)" : "var(--border)"}`,
                borderRadius: 12,
                padding: "18px 20px",
                textAlign: "left",
                cursor: "pointer",
                color: "var(--fg)",
                transition: "all 0.2s var(--ease)",
              }}
            >
              <div style={{ fontFamily: "DM Sans", fontSize: 19, fontWeight: 600, marginBottom: 4 }}>{o.v}</div>
              <div style={{ color: "var(--muted)", fontSize: 13 }}>{o.d}</div>
            </button>
          );
        })}
      </div>
      {error && <div style={{ color: "var(--danger)", fontSize: 13, marginTop: 16 }}>{error}</div>}
    </div>
  );
}

function StepTimeline({ data, update, error }) {
  const opts = ["ASAP — yesterday", "Within 1 month", "1 – 3 months out", "3+ months out", "Flexible / not sure"];
  return (
    <div>
      <h2 className="font-display" style={{ fontSize: 28, marginBottom: 8 }}>When do you need this?</h2>
      <p style={{ color: "var(--muted)", marginBottom: 28 }}>We'll be honest if we can't hit your timeline.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {opts.map((o) => {
          const sel = data.timeline === o;
          return (
            <button
              key={o}
              onClick={() => update("timeline", o)}
              style={{
                background: sel ? "var(--brand-faint)" : "rgba(255,255,255,0.02)",
                border: `1px solid ${sel ? "var(--brand)" : "var(--border)"}`,
                borderRadius: 12,
                padding: "16px 20px",
                textAlign: "left",
                cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "space-between",
                color: "var(--fg)", fontSize: 15, fontWeight: 500,
                transition: "all 0.2s var(--ease)",
              }}
            >
              {o}
              <div style={{
                width: 22, height: 22, borderRadius: "50%",
                border: `1.5px solid ${sel ? "var(--brand)" : "var(--border-strong)"}`,
                background: sel ? "var(--brand)" : "transparent",
                display: "grid", placeItems: "center",
              }}>
                {sel && <svg width="10" height="10" viewBox="0 0 10 10"><path d="M2 5L4 7L8 3" stroke="#0A0C09" strokeWidth="2" strokeLinecap="round" fill="none"/></svg>}
              </div>
            </button>
          );
        })}
      </div>
      {error && <div style={{ color: "var(--danger)", fontSize: 13, marginTop: 16 }}>{error}</div>}
    </div>
  );
}

function StepContact({ data, update, errors }) {
  return (
    <div>
      <h2 className="font-display" style={{ fontSize: 28, marginBottom: 8 }}>How can we reach you?</h2>
      <p style={{ color: "var(--muted)", marginBottom: 28 }}>We'll only use this to send your quote and follow up.</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="contact-grid">
        <div className="field">
          <label>Your name *</label>
          <input value={data.name} onChange={(e) => update("name", e.target.value)} placeholder="Ayesha Karim" />
          {errors.name && <div style={{ color: "var(--danger)", fontSize: 12 }}>{errors.name}</div>}
        </div>
        <div className="field">
          <label>Email *</label>
          <input type="email" value={data.email} onChange={(e) => update("email", e.target.value)} placeholder="ayesha@company.com" />
          {errors.email && <div style={{ color: "var(--danger)", fontSize: 12 }}>{errors.email}</div>}
        </div>
        <div className="field">
          <label>Company</label>
          <input value={data.company} onChange={(e) => update("company", e.target.value)} placeholder="Optional" />
        </div>
        <div className="field">
          <label>Phone / WhatsApp</label>
          <input value={data.phone} onChange={(e) => update("phone", e.target.value)} placeholder="+880 1704 649 409" />
        </div>
        <div className="field" style={{ gridColumn: "1 / -1" }}>
          <label>Anything else we should know?</label>
          <textarea value={data.message} onChange={(e) => update("message", e.target.value)} placeholder="Goals, constraints, links to inspiration, anything..." />
        </div>
        <div className="field" style={{ gridColumn: "1 / -1" }}>
          <label>Brief / spec (optional)</label>
          <label style={{
            border: "1px dashed var(--border-strong)", borderRadius: 12, padding: "20px",
            display: "flex", alignItems: "center", justifyContent: "center", gap: 12,
            color: "var(--muted)", cursor: "pointer", textTransform: "none", letterSpacing: "normal",
            fontFamily: "inherit", fontSize: 14,
          }}>
            <input type="file" style={{ display: "none" }} onChange={(e) => update("fileName", e.target.files[0]?.name || "")} />
            <span style={{ fontSize: 20 }}>↑</span>
            {data.fileName ? <span style={{ color: "var(--brand)" }}>{data.fileName}</span> : <span>Drop a file or click to upload — PDF, DOC, image</span>}
          </label>
        </div>
      </div>
      <style>{`@media (max-width: 600px) { .contact-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

function StepReview({ data, setStep }) {
  const rows = [
    ["Service", { web: "Website Development", app: "App Development", ai: "AI Automation", multiple: "Multiple / not sure" }[data.service] || "—", 0],
    ["Project type", data.type || "—", 1],
    ["Features", data.features.length ? data.features.join(", ") : "None selected", 2],
    ["Budget", data.budget || "—", 3],
    ["Timeline", data.timeline || "—", 4],
    ["Name", data.name || "—", 5],
    ["Email", data.email || "—", 5],
    ["Company", data.company || "—", 5],
    ["Phone", data.phone || "—", 5],
    ["Message", data.message || "—", 5],
    ["File", data.fileName || "—", 5],
  ];
  return (
    <div>
      <h2 className="font-display" style={{ fontSize: 28, marginBottom: 8 }}>Quick review.</h2>
      <p style={{ color: "var(--muted)", marginBottom: 28 }}>Everything look right? You can edit any section before submitting.</p>
      <div style={{ borderTop: "1px solid var(--border)" }}>
        {rows.map(([k, v, s]) => (
          <div key={k} style={{ display: "grid", gridTemplateColumns: "180px 1fr auto", gap: 16, padding: "16px 0", borderBottom: "1px solid var(--border)", alignItems: "center" }}>
            <div className="font-mono" style={{ fontSize: 12, color: "var(--muted)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{k}</div>
            <div style={{ color: "var(--fg-2)", fontSize: 15 }}>{v}</div>
            <button onClick={() => setStep(s)} style={{ background: "transparent", border: "none", color: "var(--brand)", fontSize: 13, fontFamily: "JetBrains Mono, monospace" }}>Edit</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function QuoteSuccess({ data }) {
  return (
    <div className="page-enter">
      <section style={{ paddingTop: 200, paddingBottom: 100, minHeight: "70vh" }}>
        <div className="container" style={{ maxWidth: 720, textAlign: "center" }}>
          <div style={{
            width: 80, height: 80, borderRadius: "50%",
            background: "var(--brand)", boxShadow: "0 0 60px var(--brand-glow)",
            display: "grid", placeItems: "center", margin: "0 auto 32px",
          }}>
            <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
              <path d="M8 16L14 22L24 10" stroke="#0A0C09" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div className="eyebrow" style={{ marginBottom: 20, justifyContent: "center" }}>Request received</div>
          <h1 className="h-display" style={{ fontSize: "clamp(40px, 6vw, 72px)", marginBottom: 24 }}>
            Thanks{data.name ? `, ${data.name.split(" ")[0]}` : ""}<span style={{ color: "var(--brand)" }}>.</span>
          </h1>
          <p className="lead" style={{ marginInline: "auto", marginBottom: 40 }}>
            We've got your brief. You'll hear from us within 24 hours — usually a lot sooner. In the meantime, anything urgent? Reach us on WhatsApp.
          </p>
          <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
            <Button to="/">← Back home</Button>
            <Button variant="ghost" to="/services">Browse services</Button>
          </div>
        </div>
      </section>
    </div>
  );
}

window.QuotePage = QuotePage;
