// ============================================================
// Migration Package Builder — the one product page
// ============================================================

function BuilderScreen({ initialConfig, onNav }) {
  const [cfg, setCfg] = React.useState(initialConfig || defaultConfig());
  const [quoteOpen, setQuoteOpen] = React.useState(false);

  React.useEffect(() => {
    if (initialConfig) setCfg({ ...defaultConfig(), ...initialConfig });
  }, []);

  const quote = priceMigration(cfg);

  const set = (key, value) => setCfg({ ...cfg, [key]: value });
  const toggleCheck = (key, choiceId) => {
    const cur = cfg[key] || [];
    const next = cur.includes(choiceId) ? cur.filter(x => x !== choiceId) : [...cur, choiceId];
    setCfg({ ...cfg, [key]: next });
  };

  return (
    <div className="builder-screen">
      <BuilderHeader />
      <div className="container">
        <div className="builder-layout">
          <div className="builder-config">
            {BUILDER_STEPS.map((step, i) => (
              <BuilderStep
                key={step.id}
                step={step}
                idx={i}
                value={cfg[step.id]}
                onChange={(v) => set(step.id, v)}
                onToggleCheck={(id) => toggleCheck(step.id, id)}
              />
            ))}
          </div>
          <BuilderSummary
            quote={quote}
            cfg={cfg}
            onRequest={() => setQuoteOpen(true)}
            onNav={onNav}
          />
        </div>
      </div>

      <BuilderMobileBar quote={quote} onRequest={() => setQuoteOpen(true)} />

      {quoteOpen && (
        <QuoteRequestModal
          cfg={cfg}
          quote={quote}
          onClose={() => setQuoteOpen(false)}
        />
      )}
    </div>
  );
}

// ── Hero / breadcrumb for the builder ──────────────────────────────
function BuilderHeader() {
  return (
    <section className="builder-hero">
      <div className="container">
        <Reveal>
          <div className="eyebrow">The shop · one product · pick-and-pay</div>
        </Reveal>
        <Reveal delay={80}>
          <h1 className="builder-title">
            {MIGRATION_PRODUCT.title.replace("The ", "").replace("Aartisan ", "")}
          </h1>
        </Reveal>
        <Reveal delay={160}>
          <p className="builder-subtitle">{MIGRATION_PRODUCT.subtitle}</p>
        </Reveal>
        <Reveal delay={240}>
          <div className="builder-hero-meta">
            <span><I.Shield size={14} /> 30-day money back</span>
            <span><I.Truck size={14} /> Onboarding email in 30 min</span>
            <span><I.Sparkles size={14} /> No forced sales calls</span>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// ── A single step section in the configurator ──────────────────────
function BuilderStep({ step, idx, value, onChange, onToggleCheck }) {
  return (
    <section className="builder-step" id={`step-${step.id}`}>
      <div className="builder-step-head">
        <span className="builder-step-num">{String(idx + 1).padStart(2, "0")}</span>
        <div>
          <h2 className="builder-step-label">{step.label}</h2>
          <p className="builder-step-help">{step.help}</p>
        </div>
      </div>
      <div className={`builder-step-body type-${step.type}`}>
        {step.type === "tiles" && step.choices.map(c => (
          <ChoiceTile
            key={c.id}
            choice={c}
            selected={value === c.id}
            onSelect={() => onChange(c.id)}
          />
        ))}
        {step.type === "tiers" && step.choices.map(c => (
          <ChoiceTier
            key={c.id}
            choice={c}
            selected={value === c.id}
            onSelect={() => onChange(c.id)}
          />
        ))}
        {step.type === "freetext" && (
          <textarea
            className="input textarea builder-freetext"
            rows={6}
            value={value || ""}
            placeholder={step.placeholder || ""}
            onChange={(e) => onChange(e.target.value)}
          />
        )}
        {step.type === "checks" && step.choices.map(c => (
          <ChoiceCheck
            key={c.id}
            choice={c}
            selected={(value || []).includes(c.id) || c.required}
            disabled={c.required}
            onToggle={() => !c.required && onToggleCheck(c.id)}
          />
        ))}
      </div>
    </section>
  );
}

// ── Choice variations ──────────────────────────────────────────────
function priceTag(c) {
  if (c.monthly) return `$${c.monthly.toLocaleString()}/mo`;
  if (c.required) return "Included";
  if ((c.priceAdd ?? 0) === 0) return "Included";
  if (c.priceAdd < 0) return `−${fmtPrice(-c.priceAdd)}`;
  if (c.multiplier && c.multiplier > 1) return `+${Math.round((c.multiplier - 1) * 100)}%`;
  return `+${fmtPrice(c.priceAdd)}`;
}

function ChoiceTile({ choice, selected, onSelect }) {
  return (
    <button
      type="button"
      className={`choice-tile ${selected ? "selected" : ""}`}
      onClick={onSelect}
      aria-pressed={selected}
    >
      <div className="choice-tile-top">
        <span className="choice-tile-label">{choice.label}</span>
        {choice.badge && <span className="choice-badge">{choice.badge}</span>}
      </div>
      {choice.sub && <span className="choice-tile-sub">{choice.sub}</span>}
      <span className="choice-tile-price">{priceTag(choice)}</span>
      {selected && (
        <span className="choice-tile-check"><I.Check size={14} /></span>
      )}
    </button>
  );
}

function ChoiceTier({ choice, selected, onSelect }) {
  return (
    <button
      type="button"
      className={`choice-tier ${selected ? "selected" : ""}`}
      onClick={onSelect}
      aria-pressed={selected}
    >
      <span className="choice-tier-radio">
        {selected && <span className="choice-tier-dot" />}
      </span>
      <span className="choice-tier-label">
        {choice.label}
        {choice.sub && <span className="choice-tier-sub"> — {choice.sub}</span>}
      </span>
      {choice.badge && <span className="choice-badge">{choice.badge}</span>}
      <span className="choice-tier-price">{priceTag(choice)}</span>
    </button>
  );
}

function ChoiceCheck({ choice, selected, disabled, onToggle }) {
  return (
    <button
      type="button"
      className={`choice-check ${selected ? "selected" : ""} ${disabled ? "disabled" : ""}`}
      onClick={onToggle}
      aria-pressed={selected}
      disabled={disabled}
    >
      <span className="choice-check-box">
        {selected && <I.Check size={14} />}
      </span>
      <span className="choice-check-text">
        <span className="choice-check-label">
          {choice.label}
          {choice.required && <span className="choice-required-tag">Required</span>}
        </span>
        {choice.sub && <span className="choice-check-sub">{choice.sub}</span>}
      </span>
      <span className="choice-check-price">{priceTag(choice)}</span>
    </button>
  );
}

// ── Summary panel (sticky right side) ──────────────────────────────
function BuilderSummary({ quote, cfg, onRequest, onNav }) {
  return (
    <aside className="builder-summary">
      <div className="builder-summary-card">
        <div className="kicker" style={{ marginBottom: 4 }}>Your quote</div>
        <div className="builder-summary-title">{MIGRATION_PRODUCT.title}</div>

        <div className="builder-price-block">
          <PriceCounter value={quote.total} />
          <div className="builder-price-sub">
            <span>One-time</span>
            <span className="builder-divider-dot">·</span>
            <span>Est. <strong>{quote.days} days</strong> to launch</span>
          </div>
          {quote.monthly > 0 && (
            <div className="builder-monthly">
              + <strong>${quote.monthly}/mo</strong> care plan
            </div>
          )}
        </div>

        <hr className="divider-dashed" />

        <div className="builder-lines">
          {quote.lines.filter(l => l.section === "core").map((l, i) => (
            <BuilderLine key={i} line={l} />
          ))}
        </div>

        {quote.lines.some(l => l.section === "addons") && (
          <>
            <div className="builder-lines-sub">Add-ons</div>
            <div className="builder-lines">
              {quote.lines.filter(l => l.section === "addons").map((l, i) => (
                <BuilderLine key={i} line={l} />
              ))}
            </div>
          </>
        )}
        {quote.lines.some(l => l.section === "care") && (
          <>
            <div className="builder-lines-sub">Care plan</div>
            <div className="builder-lines">
              {quote.lines.filter(l => l.section === "care").map((l, i) => (
                <BuilderLine key={i} line={l} />
              ))}
            </div>
          </>
        )}

        <hr className="divider-dashed" />

        <div className="builder-total">
          <span>Total</span>
          <span>{fmtPrice(quote.total)}</span>
        </div>
        {quote.monthly > 0 && (
          <div className="builder-total-monthly">
            <span>Then monthly</span>
            <span>${quote.monthly}/mo</span>
          </div>
        )}

        <button className="btn btn-accent full" onClick={onRequest} style={{ marginTop: 16 }}>
          Request this quote <I.ArrowRight size={16} />
        </button>

        <p style={{ fontSize: 11, color: "var(--fg-3)", textAlign: "center", margin: "12px 0 0", lineHeight: 1.5 }}>
          We'll review your config and reply within 24 hours. No sales call required.
        </p>
      </div>
    </aside>
  );
}

function BuilderLine({ line }) {
  return (
    <div className={`builder-line ${line.informational ? "informational" : ""}`}>
      <div className="builder-line-label">
        {line.stepLabel && <span className="builder-line-step">{line.stepLabel}</span>}
        <span>{line.label}</span>
      </div>
      <div className="builder-line-price">
        {line.monthly ? `$${line.price}/mo` :
         (line.price === 0 ? <span style={{ color: "var(--fg-3)" }}>Included</span> :
          (line.price < 0 ? `−${fmtPrice(-line.price)}` : `+${fmtPrice(line.price)}`))}
      </div>
    </div>
  );
}

// Animated price counter
function PriceCounter({ value }) {
  const [shown, setShown] = React.useState(value);
  const prev = React.useRef(value);
  React.useEffect(() => {
    const from = prev.current;
    const to = value;
    if (from === to) return;
    const duration = 360;
    const start = performance.now();
    let raf;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setShown(Math.round(from + (to - from) * eased));
      if (t < 1) raf = requestAnimationFrame(tick);
      else prev.current = to;
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  return <span className="builder-price">{fmtPrice(shown)}</span>;
}

// ── Quote request modal ────────────────────────────────────────────
function QuoteRequestModal({ cfg, quote, onClose }) {
  const [form, setForm] = React.useState({ name: "", email: "", storeUrl: "", message: "" });
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const summary = summarizeConfig(cfg);

  const set = (k, v) => { setForm({ ...form, [k]: v }); setErrors({ ...errors, [k]: null }); };
  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = "We'd like to know who we're replying to";
    if (!/^\S+@\S+\.\S+$/.test(form.email)) errs.email = "We'll need a working email";
    if (!form.storeUrl.trim()) errs.storeUrl = "Your current store URL helps us prepare";
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;
    setSubmitting(true);
    try {
      const res = await fetch("/api/send-quote", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          storeUrl: form.storeUrl,
          message: form.message,
          quote: { total: quote.total, days: quote.days, monthly: quote.monthly, lines: quote.lines },
          summary,
          cfg,
        }),
      });
      if (!res.ok) throw new Error("send failed");
      setSubmitted(true);
    } catch {
      setErrors({ _global: "Something went wrong — please email blake@aartisan.io directly." });
    } finally {
      setSubmitting(false);
    }
  };

  // Close on Esc
  React.useEffect(() => {
    const fn = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", fn);
    return () => document.removeEventListener("keydown", fn);
  }, [onClose]);

  return (
    <div className="quote-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="quote-modal">
        <button className="icon-btn quote-close" onClick={onClose} aria-label="Close">
          <I.X size={16} />
        </button>

        {submitted ? (
          <div className="quote-success">
            <div className="quote-success-check">
              <I.Check size={56} style={{ color: "var(--color-plum-900)" }} />
            </div>
            <div className="eyebrow">Quote requested</div>
            <h2 className="quote-success-title">Talk soon.</h2>
            <p>
              Got it. We sent your config + contact info to Blake — you'll hear back within 24 hours
              (usually much sooner) at <strong>{form.email}</strong> with a confirmed quote and
              next steps. No follow-up email sequence, ever.
            </p>
            <button className="btn" onClick={onClose}>Back to the builder</button>
          </div>
        ) : (
          <>
            <div className="quote-modal-head">
              <div className="kicker">Step 2 of 2</div>
              <h2 className="quote-modal-title">Send this quote to Blake.</h2>
              <p className="quote-modal-sub">
                Drop your details below and we'll reply within 24 hours with a confirmed quote and a kickoff date. No sales script.
              </p>
            </div>

            <div className="quote-modal-body">
              <div className="quote-summary">
                <div className="kicker">Your configured package</div>
                <div className="quote-summary-total">
                  <span>{fmtPrice(quote.total)}</span>
                  <span className="quote-summary-days">Est. {quote.days} days</span>
                </div>
                {quote.monthly > 0 && (
                  <div className="quote-summary-monthly">
                    + ${quote.monthly}/mo care plan
                  </div>
                )}
                <ul className="quote-summary-bullets">
                  {summary.map((s, i) => <li key={i}>{s}</li>)}
                  {quote.lines.filter(l => l.section === "addons").map((l, i) => (
                    <li key={"a" + i}>{l.label}</li>
                  ))}
                </ul>
              </div>

              <form onSubmit={submit} className="quote-form">
                <div>
                  <label className="field-label">Your name</label>
                  <input
                    className={`input ${errors.name ? "error" : ""}`}
                    value={form.name}
                    onChange={(e) => set("name", e.target.value)}
                    autoFocus
                  />
                  {errors.name && <span className="field-error">{errors.name}</span>}
                </div>
                <div>
                  <label className="field-label">Email</label>
                  <input
                    className={`input ${errors.email ? "error" : ""}`}
                    value={form.email}
                    onChange={(e) => set("email", e.target.value)}
                    placeholder="you@store.com"
                  />
                  {errors.email && <span className="field-error">{errors.email}</span>}
                </div>
                <div>
                  <label className="field-label">Current store URL</label>
                  <input
                    className={`input ${errors.storeUrl ? "error" : ""}`}
                    value={form.storeUrl}
                    onChange={(e) => set("storeUrl", e.target.value)}
                    placeholder="https://shop.example.com"
                  />
                  {errors.storeUrl && <span className="field-error">{errors.storeUrl}</span>}
                </div>
                <div>
                  <label className="field-label">Anything we should know? <span style={{ color: "var(--fg-3)", fontWeight: 400, textTransform: "none", letterSpacing: 0 }}>(optional)</span></label>
                  <textarea
                    className="input textarea"
                    rows="3"
                    value={form.message}
                    onChange={(e) => set("message", e.target.value)}
                    placeholder="Deadline pressure, B2B needs, unusual apps, anything else…"
                  />
                </div>
                {errors._global && (
                  <div style={{ color: "var(--color-danger)", fontSize: 13, textAlign: "center", lineHeight: 1.5 }}>
                    {errors._global}
                  </div>
                )}
                <button className="btn btn-accent full" type="submit" disabled={submitting}>
                  {submitting ? "Sending…" : "Send to Blake"} {!submitting && <I.ArrowRight size={16} />}
                </button>
                <p style={{ fontSize: 11, color: "var(--fg-3)", textAlign: "center", margin: 0, lineHeight: 1.5 }}>
                  Sent to <strong>blake@aartisan.io</strong> · We reply within 24h · No drip emails
                </p>
              </form>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ── Mobile sticky bottom bar ───────────────────────────────────────
function BuilderMobileBar({ quote, onRequest }) {
  const [activeStep, setActiveStep] = React.useState(0);
  const total = BUILDER_STEPS.length;

  // Track which step is currently in view
  React.useEffect(() => {
    const steps = document.querySelectorAll(".builder-step");
    if (!steps.length) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const idx = Array.from(steps).indexOf(entry.target);
            if (idx !== -1) setActiveStep(idx);
          }
        });
      },
      { rootMargin: "-35% 0px -55% 0px", threshold: 0 }
    );
    steps.forEach((el) => obs.observe(el));
    return () => obs.disconnect();
  }, []);

  const progress = ((activeStep + 1) / total) * 100;

  return (
    <div className="builder-mobile-bar">
      <div className="builder-mobile-bar-track">
        <div className="builder-mobile-bar-fill" style={{ width: `${progress}%` }} />
      </div>
      <div className="builder-mobile-bar-body">
        <div className="builder-mobile-bar-info">
          <span className="builder-mobile-bar-step">Step {activeStep + 1} of {total}</span>
          <span className="builder-mobile-bar-price">{fmtPrice(quote.total)}</span>
          {quote.monthly > 0 && (
            <span className="builder-mobile-bar-monthly">+${quote.monthly}/mo</span>
          )}
        </div>
        <button className="btn btn-accent btn-sm" onClick={onRequest}>
          Request quote <I.ArrowRight size={13} />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { BuilderScreen, QuoteRequestModal });
