// Multi-step order form. All fields from the source Google Form:
//  - email
//  - name
//  - need-by date (with lead-time + blackout-date validation)
//  - shipping address (conditional on local vs ship)
//  - cookie type (4 options: regular / vegan / GF / vegan+GF)
//  - quantity (min 12, must be in dozens)
//  - theme
//  - gift note (optional)
//  - payment method (Zelle / Paypal / Venmo, + Cash if local)

const SUBMIT_URL = "https://script.google.com/macros/s/AKfycby8X80PYzCxECDoymg3R75Zy22f5u3xMhEMOFO5pCYLGy33Ut6p4v6aDKvq5itZ_eZC/exec";

const COOKIE_TYPES = [
  { id: "regular",  title: "Regular sugar cookie",   sub: "Classic sugar cookie with regular icing (meringue powder base)." },
  { id: "vegan",    title: "Vegan sugar cookie",     sub: "Vegan cookie with vegan icing (aquafaba from chickpeas base).", accent: { label: "Vegan", bg: "oklch(0.93 0.06 130)", fg: "oklch(0.35 0.08 130)" } },
  { id: "gf",       title: "Gluten-free sugar cookie", sub: "Gluten-free cookie with regular icing.", accent: { label: "GF", bg: "oklch(0.93 0.06 80)", fg: "oklch(0.4 0.07 70)" } },
  { id: "vegan_gf", title: "Vegan + gluten-free",    sub: "Vegan, gluten-free cookie with vegan icing.", accent: { label: "Vegan · GF", bg: "oklch(0.93 0.06 100)", fg: "oklch(0.38 0.08 100)" } },
];

const PAYMENTS = [
  { id: "venmo",  title: "Venmo",  sub: "@nadyasharif" },
  { id: "zelle",  title: "Zelle",  sub: "nadyabsharif@gmail.com" },
  { id: "paypal", title: "PayPal", sub: "paypal.me/nadyasharif" },
  { id: "cash",   title: "Cash",   sub: "LA pickup only", localOnly: true },
];

// June 11–17 2026 and July 24–26 2026 (form mentions these as unavailable)
const BLACKOUTS = [
  { from: "2026-06-11", to: "2026-06-17", label: "June 11–17" },
  { from: "2026-07-24", to: "2026-07-26", label: "July 24–26" },
];

const todayISO = () => new Date().toISOString().slice(0, 10);

function isBlackout(iso) {
  return BLACKOUTS.find((b) => iso >= b.from && iso <= b.to);
}

function daysBetween(aISO, bISO) {
  const a = new Date(aISO + "T00:00:00");
  const b = new Date(bISO + "T00:00:00");
  return Math.round((b - a) / 86400000);
}

function fmtDate(iso) {
  if (!iso) return "";
  const d = new Date(iso + "T00:00:00");
  return d.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", year: "numeric" });
}

// ───────────────────────────────────────────────────────────────────────────
// Stepper at the top of the form
// ───────────────────────────────────────────────────────────────────────────
function Stepper({ step, steps }) {
  const isMobile = useIsMobile();
  return (
    <div style={{ display: "flex", alignItems: "center", gap: isMobile ? 6 : 10, marginBottom: 32, flexWrap: "wrap" }}>
      {steps.map((label, i) => {
        const done = i < step;
        const active = i === step;
        const showLabel = !isMobile || active;
        return (
          <React.Fragment key={label}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, opacity: active || done ? 1 : 0.5 }}>
              <div style={{
                width: 22, height: 22, borderRadius: 999,
                background: done ? "var(--terra)" : active ? "var(--butter)" : "transparent",
                border: `1.5px solid ${done || active ? "var(--terra)" : "var(--rule)"}`,
                color: done ? "var(--butter)" : "var(--cocoa)",
                display: "grid", placeItems: "center",
                fontSize: 12, fontWeight: 600,
                flexShrink: 0,
              }}>
                {done ? "✓" : i + 1}
              </div>
              {showLabel && <div style={{ fontSize: 13, color: active ? "var(--cocoa)" : "var(--cocoa-soft)", fontWeight: active ? 500 : 400 }}>{label}</div>}
            </div>
            {i < steps.length - 1 && <div style={{ flex: "0 0 14px", height: 1, background: "var(--rule)" }} />}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// Date picker — native input + computed validation messaging
// ───────────────────────────────────────────────────────────────────────────
function DateField({ value, onChange, fulfillment, error }) {
  const min = useMemo(() => {
    const d = new Date();
    const minDays = fulfillment === "ship" ? 21 : 7;
    d.setDate(d.getDate() + minDays);
    return d.toISOString().slice(0, 10);
  }, [fulfillment]);

  const computed = useMemo(() => {
    if (!value) return null;
    const days = daysBetween(todayISO(), value);
    const minDays = fulfillment === "ship" ? 21 : 7;
    const black = isBlackout(value);
    if (black) return { tone: "bad", msg: `That date falls in a closed window (${black.label}). Please pick another date.` };
    if (days < minDays) return { tone: "bad", msg: `Need at least ${minDays} days. ${fulfillment === "ship" ? "Shipping" : "Local pickup"} requires a ${fulfillment === "ship" ? "3-week" : "1-week"} minimum lead time.` };
    return { tone: "good", msg: `${fmtDate(value)} — that's ${days} days out. Plenty of time.` };
  }, [value, fulfillment]);

  return (
    <div>
      <input
        type="date"
        value={value || ""}
        min={min}
        onChange={(e) => onChange(e.target.value)}
        style={{
          width: "100%",
          background: "var(--butter)",
          border: `1px solid ${error ? "var(--berry)" : "var(--rule)"}`,
          borderRadius: 10,
          padding: "12px 14px",
          fontSize: 15,
          outline: "none",
          color: "var(--cocoa)",
          fontFamily: "inherit",
        }}
      />
      {computed && (
        <div style={{
          marginTop: 10, padding: "10px 12px", borderRadius: 10,
          background: computed.tone === "good" ? "oklch(0.92 0.05 130 / 0.5)" : "oklch(0.92 0.05 25 / 0.5)",
          border: `1px solid ${computed.tone === "good" ? "oklch(0.7 0.1 130)" : "oklch(0.7 0.1 25)"}`,
          fontSize: 13.5,
          color: computed.tone === "good" ? "oklch(0.35 0.08 130)" : "oklch(0.4 0.12 25)",
          display: "flex", alignItems: "flex-start", gap: 8,
        }}>
          <span style={{ marginTop: 2, width: 8, height: 8, borderRadius: 999, flexShrink: 0,
            background: computed.tone === "good" ? "var(--moss)" : "var(--berry)" }} />
          <span>{computed.msg}</span>
        </div>
      )}
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// Quantity stepper — must be in dozens, min 1 dozen
// ───────────────────────────────────────────────────────────────────────────
function DozenStepper({ value, onChange }) {
  const dozens = Math.max(1, Math.round(value / 12) || 1);
  const set = (n) => onChange(Math.max(1, n) * 12);
  const low = 40 * dozens, high = 60 * dozens;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <button type="button" onClick={() => set(dozens - 1)} disabled={dozens <= 1}
          style={{
            width: 44, height: 44, borderRadius: 999,
            border: "1px solid var(--rule)", background: "var(--butter)",
            fontSize: 20, cursor: dozens <= 1 ? "not-allowed" : "pointer",
            opacity: dozens <= 1 ? 0.4 : 1, color: "var(--cocoa)",
          }}>−</button>
        <div style={{ flex: 1, textAlign: "center", padding: "10px 0", background: "var(--butter)", border: "1px solid var(--rule)", borderRadius: 12 }}>
          <div className="serif" style={{ fontSize: 32, lineHeight: 1, color: "var(--cocoa)" }}>{dozens} <span style={{ fontSize: 16, color: "var(--cocoa-soft)" }}>{dozens === 1 ? "dozen" : "dozens"}</span></div>
          <div style={{ fontSize: 13, color: "var(--cocoa-soft)", marginTop: 4 }}>{dozens * 12} cookies</div>
        </div>
        <button type="button" onClick={() => set(dozens + 1)}
          style={{
            width: 44, height: 44, borderRadius: 999,
            border: "1px solid var(--rule)", background: "var(--butter)",
            fontSize: 20, cursor: "pointer", color: "var(--cocoa)",
          }}>+</button>
      </div>
      <div style={{ fontSize: 13.5, color: "var(--cocoa-soft)", textAlign: "center" }}>
        Estimated cookies: <span style={{ color: "var(--cocoa)", fontWeight: 500 }}>${low}–${high}</span>
        <span style={{ opacity: 0.6 }}> · price depends on design complexity</span>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// The form
// ───────────────────────────────────────────────────────────────────────────
function OrderForm() {
  const [step, setStep] = useState(0);
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");

  const [data, setData] = useState({
    name: "",
    email: "",
    fulfillment: "local",   // "local" | "ship"
    address: "",
    needBy: "",
    cookieType: "",
    quantity: 12,
    theme: "",
    giftNote: "",
    payment: "",
  });

  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const errors = useMemo(() => {
    const e = {};
    if (step === 0) {
      if (!data.name.trim()) e.name = "Please add your name.";
      if (!data.email.trim() || !/^\S+@\S+\.\S+$/.test(data.email)) e.email = "Please add a valid email.";
    }
    if (step === 1) {
      if (!data.needBy) e.needBy = "Pick a date.";
      else {
        const minDays = data.fulfillment === "ship" ? 21 : 7;
        if (daysBetween(todayISO(), data.needBy) < minDays) e.needBy = `Needs at least ${minDays} days.`;
        if (isBlackout(data.needBy)) e.needBy = "That date is in a closed window.";
      }
      if (data.fulfillment === "ship" && !data.address.trim()) e.address = "Shipping needs an address.";
    }
    if (step === 2) {
      if (!data.cookieType) e.cookieType = "Pick a cookie type.";
      if (data.quantity < 12) e.quantity = "Minimum 1 dozen.";
      if (!data.theme.trim()) e.theme = "Tell me a bit about the theme.";
    }
    if (step === 3) {
      if (!data.payment) e.payment = "Pick a payment method.";
    }
    return e;
  }, [step, data]);

  const canAdvance = Object.keys(errors).length === 0;

  const steps = ["You", "When & where", "Cookies", "Payment"];

  async function next() {
    if (!canAdvance) return;
    if (step < steps.length - 1) { setStep(step + 1); return; }
    setSubmitting(true);
    setSubmitError("");
    try {
      await fetch(SUBMIT_URL, {
        method: "POST",
        body: JSON.stringify(data),
      });
      setSubmitted(true);
    } catch (err) {
      setSubmitError("Something went wrong. Please try again or DM on Instagram.");
    } finally {
      setSubmitting(false);
    }
  }
  function back() {
    if (step > 0) setStep(step - 1);
  }

  if (submitted) return <SubmittedView data={data} onReset={() => { setSubmitted(false); setStep(0); setData({ ...data, theme: "", giftNote: "" }); }} />;

  return (
    <div style={{
      background: "var(--cream)",
      borderRadius: 24,
      padding: "36px clamp(20px, 4vw, 48px)",
      border: "1px solid var(--rule)",
      boxShadow: "0 1px 0 oklch(1 0 0 / 0.4) inset, 0 24px 48px -32px oklch(0.4 0.05 50 / 0.25)",
    }}>
      <Stepper step={step} steps={steps} />

      {step === 0 && <StepYou data={data} set={set} errors={errors} />}
      {step === 1 && <StepWhen data={data} set={set} errors={errors} />}
      {step === 2 && <StepCookies data={data} set={set} errors={errors} />}
      {step === 3 && <StepPayment data={data} set={set} errors={errors} />}

      {submitError && (
        <div style={{ marginTop: 16, padding: "10px 14px", borderRadius: 10, background: "oklch(0.92 0.05 25 / 0.5)", border: "1px solid oklch(0.7 0.1 25)", fontSize: 13.5, color: "oklch(0.4 0.12 25)" }}>
          {submitError}
        </div>
      )}
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 32, gap: 12, flexWrap: "wrap" }}>
        <Button variant="ghost" onClick={back} disabled={step === 0 || submitting}>← Back</Button>
        <Button variant="primary" onClick={next} disabled={!canAdvance || submitting}>
          {submitting ? "Sending…" : step === steps.length - 1 ? "Send request" : "Continue →"}
        </Button>
      </div>
    </div>
  );
}

// ── Step 1: contact ────────────────────────────────────────────────────────
function StepYou({ data, set, errors }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      <SectionTitle eyebrow="Step 01" title="Let's start with you" />
      <div>
        <Label required>Your name</Label>
        <TextInput value={data.name} onChange={(v) => set("name", v)} placeholder="Friends call you…" error={!!errors.name} />
        <FieldError>{errors.name}</FieldError>
      </div>
      <div>
        <Label required hint="A copy of your responses will be emailed here.">Email</Label>
        <TextInput value={data.email} onChange={(v) => set("email", v)} placeholder="you@example.com" type="email" error={!!errors.email} />
        <FieldError>{errors.email}</FieldError>
      </div>
    </div>
  );
}

// ── Step 2: when & where ───────────────────────────────────────────────────
function StepWhen({ data, set, errors }) {
  const isMobile = useIsMobile();
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      <SectionTitle eyebrow="Step 02" title="When do you need them?" />

      <div>
        <Label required>Pickup, drop-off, or shipping?</Label>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 12 }}>
          <PillOption
            selected={data.fulfillment === "local"}
            onClick={() => set("fulfillment", "local")}
            title="Local to LA"
            sub="Pickup or drop-off. 1-week minimum."
          />
          <PillOption
            selected={data.fulfillment === "ship"}
            onClick={() => set("fulfillment", "ship")}
            title="Ship anywhere in the US"
            sub="3-week minimum. $15–$35 ship cost confirmed later."
          />
        </div>
      </div>

      <div>
        <Label required hint={data.fulfillment === "ship"
          ? "The date the cookies should arrive — not the date of your event. I aim to arrive 1 day early in case of USPS delays."
          : "The date you'll pick up or have the cookies dropped off."}>
          {data.fulfillment === "ship" ? "Arrive-by date" : "Pickup / drop-off date"}
        </Label>
        <DateField value={data.needBy} onChange={(v) => set("needBy", v)} fulfillment={data.fulfillment} error={!!errors.needBy} />
      </div>

      {data.fulfillment === "ship" && (
        <div>
          <Label required>Shipping address</Label>
          <Textarea value={data.address} onChange={(v) => set("address", v)} rows={3} placeholder={"Name\nStreet address, Apt / Suite\nCity, State, ZIP"} error={!!errors.address} />
          <FieldError>{errors.address}</FieldError>
        </div>
      )}

      <BlackoutNotice />
    </div>
  );
}

function BlackoutNotice() {
  return (
    <div style={{
      display: "flex", gap: 12, padding: "12px 14px",
      background: "oklch(0.95 0.03 80)",
      border: "1px dashed var(--crust)",
      borderRadius: 12,
    }}>
      <div style={{ width: 6, borderRadius: 999, background: "var(--terra)", flexShrink: 0 }} />
      <div style={{ fontSize: 13.5, color: "var(--cocoa-soft)", lineHeight: 1.5 }}>
        <span style={{ color: "var(--cocoa)", fontWeight: 500 }}>Closed windows: </span>
        June 11–17 &amp; July 24–26 (no pickups or shipping).
      </div>
    </div>
  );
}

// ── Step 3: cookie type, qty, theme, gift note ─────────────────────────────
function StepCookies({ data, set, errors }) {
  const isMobile = useIsMobile();
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 26 }}>
      <SectionTitle eyebrow="Step 03" title="Your cookies" />

      <div>
        <Label required hint="Vegan and GF cookies are made in a kitchen with equipment exposed to gluten and dairy.">Type of sugar cookie</Label>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 12 }}>
          {COOKIE_TYPES.map((c) => (
            <PillOption
              key={c.id}
              selected={data.cookieType === c.id}
              onClick={() => set("cookieType", c.id)}
              title={c.title}
              sub={c.sub}
              accent={c.accent}
            />
          ))}
        </div>
        <FieldError>{errors.cookieType}</FieldError>
      </div>

      <div>
        <Label required hint="Minimum 1 dozen (12). $40–60 per dozen depending on detail.">How many?</Label>
        <DozenStepper value={data.quantity} onChange={(v) => set("quantity", v)} />
      </div>

      <div>
        <Label required hint="A short description is plenty — we'll dig into colors, inspo pics, and sketches over Instagram DM.">Theme / occasion</Label>
        <Textarea value={data.theme} onChange={(v) => set("theme", v)} rows={3} placeholder="e.g. 'Mara's baby shower — sage green, peach, eucalyptus, small floral motifs.'" error={!!errors.theme} />
        <FieldError>{errors.theme}</FieldError>
      </div>

      <div>
        <Label hint="Optional. If this is a gift, tell me anything you'd like included on a note.">Gift note</Label>
        <Textarea value={data.giftNote} onChange={(v) => set("giftNote", v)} rows={2} placeholder="(optional) e.g. 'Congrats Sam — proud of you. — J'" />
      </div>
    </div>
  );
}

// ── Step 4: payment ────────────────────────────────────────────────────────
function StepPayment({ data, set, errors }) {
  const isMobile = useIsMobile();
  const opts = PAYMENTS.filter((p) => !p.localOnly || data.fulfillment === "local");
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      <SectionTitle eyebrow="Step 04" title="How will you pay?" />

      <div style={{ fontSize: 14, color: "var(--cocoa-soft)", lineHeight: 1.55, padding: "12px 14px", background: "var(--butter)", borderRadius: 12, border: "1px solid var(--rule)" }}>
        Please pay at least <span style={{ color: "var(--cocoa)", fontWeight: 500 }}>one week before</span> your {data.fulfillment === "ship" ? "ship" : "pickup"} date.
        {data.fulfillment === "ship" && " For shipping, send only the per-dozen amount — I'll confirm the shipping cost once they're packed."}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 12 }}>
        {opts.map((p) => (
          <PillOption
            key={p.id}
            selected={data.payment === p.id}
            onClick={() => set("payment", p.id)}
            title={p.title}
            sub={p.sub}
          />
        ))}
      </div>
      <FieldError>{errors.payment}</FieldError>

      <Summary data={data} />
    </div>
  );
}

function SectionTitle({ eyebrow, title }) {
  return (
    <div>
      <div style={{ fontSize: 11, letterSpacing: 2, textTransform: "uppercase", color: "var(--terra)", fontWeight: 500 }}>{eyebrow}</div>
      <div className="serif" style={{ fontSize: 30, lineHeight: 1.1, marginTop: 6, color: "var(--cocoa)" }}>{title}</div>
    </div>
  );
}

function Summary({ data }) {
  const ct = COOKIE_TYPES.find((c) => c.id === data.cookieType);
  const dozens = data.quantity / 12;
  const low = 40 * dozens, high = 60 * dozens;
  return (
    <div style={{
      background: "var(--butter)", borderRadius: 14, border: "1px solid var(--rule)",
      padding: "18px 20px", display: "flex", flexDirection: "column", gap: 10,
    }}>
      <div style={{ fontSize: 12, letterSpacing: 1.5, textTransform: "uppercase", color: "var(--cocoa-soft)" }}>Order summary</div>
      <Row k="For" v={data.name || "—"} />
      <Row k="When" v={data.needBy ? fmtDate(data.needBy) : "—"} />
      <Row k="Fulfillment" v={data.fulfillment === "ship" ? "Ship anywhere in the US" : "Local LA pickup / drop-off"} />
      <Row k="Cookies" v={ct ? `${dozens} dozen ${ct.title.toLowerCase()}` : "—"} />
      <Row k="Theme" v={data.theme || "—"} truncate />
      <Row k="Estimated" v={`$${low}–$${high}${data.fulfillment === "ship" ? " + shipping" : ""}`} />
    </div>
  );
}

function Row({ k, v, truncate }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 16, fontSize: 14, lineHeight: 1.4 }}>
      <div style={{ color: "var(--cocoa-soft)" }}>{k}</div>
      <div style={{ color: "var(--cocoa)", ...(truncate ? { overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" } : {}) }}>{v}</div>
    </div>
  );
}

// ── Submitted view ─────────────────────────────────────────────────────────
function SubmittedView({ data, onReset }) {
  return (
    <div style={{
      background: "var(--cream)", borderRadius: 24, border: "1px solid var(--rule)",
      padding: "48px clamp(24px, 5vw, 64px)", textAlign: "center",
      boxShadow: "0 24px 48px -32px oklch(0.4 0.05 50 / 0.25)",
    }}>
      <div style={{ display: "flex", justifyContent: "center", gap: 10, marginBottom: 12 }}>
        <Cookie size={56} dough="oklch(0.78 0.07 70)" ring="oklch(0.93 0.05 80)" dots="oklch(0.55 0.14 45)" rotate={-10} />
        <Cookie size={64} dough="oklch(0.82 0.06 80)" ring="oklch(0.95 0.04 90)" dots="oklch(0.55 0.13 25)" rotate={6} dotCount={8} />
        <Cookie size={56} dough="oklch(0.76 0.06 60)" ring="oklch(0.93 0.05 80)" dots="oklch(0.55 0.08 130)" rotate={-4} dotCount={5} />
      </div>
      <div className="script" style={{ fontSize: 24, color: "var(--terra)" }}>thank you!</div>
      <div className="serif" style={{ fontSize: 38, lineHeight: 1.1, color: "var(--cocoa)", marginTop: 4 }}>Your request is in.</div>
      <div style={{ maxWidth: 440, margin: "16px auto 0", color: "var(--cocoa-soft)", fontSize: 15, lineHeight: 1.6 }}>
        I'll get back to you at <span style={{ color: "var(--cocoa)", fontWeight: 500 }}>{data.email}</span> within a day or two. From there we'll chat about colors, inspo and design over Instagram DM, and I'll send back sketches.
      </div>
      <div style={{ marginTop: 28 }}>
        <Button variant="ghost" onClick={onReset}>Start another request</Button>
      </div>
    </div>
  );
}

Object.assign(window, { OrderForm });
