// FENIX UNIFORM - Quote Request Page (multi-step)
const { useState: useStateQ, useEffect: useEffectQ } = React;

const QUOTE_TWEAKS = /*EDITMODE-BEGIN*/{
  "accent": "#E63329"
}/*EDITMODE-END*/;

// Google Apps Script Web App endpoint — appends submissions to a Google Sheet.
// Body is sent as text/plain to avoid a CORS preflight that Apps Script does not support.
const QUOTE_ENDPOINT = 'https://script.google.com/macros/s/AKfycbwyA1EpTw9z28_nRiLJQJspov5wW_M0CGjbcAhN4iIlu2YlnSu6OvzqUfiru4mJbEVf/exec';

const PRODUCT_TYPES = [
  { key: "uniform", code: "UF", icon: "▦" },
  { key: "shirt", code: "TS", icon: "◆" },
  { key: "pants", code: "PT", icon: "▮" },
  { key: "cap", code: "CP", icon: "◓" },
];

const QTY_RANGES = ["12-50", "51-100", "101-300", "301-1,000", "1,000+"];
const PRINT_KEYS = ["screen", "embroidery", "dtg", "sublimation", "unsure"];
const TIMELINE_KEYS = ["urgent", "normal", "relaxed", "none"];

const Stepper = ({ step, accent }) => {
  const { t } = window.useLang();
  const stepKeys = ["quote.step.0", "quote.step.1", "quote.step.2"];
  return (
    <div className="flex items-center gap-3 mb-12">
      {stepKeys.map((key, i) => (
        <React.Fragment key={i}>
          <div className="flex items-center gap-3">
            <div
              className="w-9 h-9 flex items-center justify-center font-black text-sm border transition-all"
              style={{
                background: i < step ? accent : i === step ? accent : "transparent",
                borderColor: i <= step ? accent : "rgba(255,255,255,0.15)",
                color: i <= step ? "#0a0a0a" : "rgba(255,255,255,0.4)",
              }}
            >
              {i < step ? "✓" : String(i + 1).padStart(2, "0")}
            </div>
            <div className="hidden sm:block">
              <div className="font-mono text-[9px] tracking-[0.2em] text-white/40">{t('quote.step.indicator')} {i + 1}</div>
              <div className={i <= step ? "text-white font-bold text-sm" : "text-white/40 text-sm"}>{t(key)}</div>
            </div>
          </div>
          {i < stepKeys.length - 1 && (
            <div className="flex-1 h-px" style={{ background: i < step ? accent : "rgba(255,255,255,0.1)" }} />
          )}
        </React.Fragment>
      ))}
    </div>
  );
};

const Choice = ({ active, onClick, children, accent }) => (
  <button
    type="button"
    onClick={onClick}
    className="text-left p-5 border transition-all"
    style={{
      background: active ? `${accent}14` : "rgba(255,255,255,0.02)",
      borderColor: active ? accent : "rgba(255,255,255,0.1)",
    }}
  >
    {children}
  </button>
);

const QField = ({ label, value, onChange, required, placeholder, type = "text" }) => (
  <label className="block">
    <div className="font-mono text-[10px] tracking-[0.25em] text-white/40 mb-2">
      {label.toUpperCase()} {required && <span style={{ color: "var(--accent)" }}>*</span>}
    </div>
    <input
      type={type}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      className="w-full bg-transparent border border-white/15 px-4 py-3.5 text-white text-base focus:outline-none focus:border-white transition"
    />
  </label>
);

const QuoteApp = () => {
  const [tw, setTweak] = window.useTweaks(QUOTE_TWEAKS);
  const accent = tw.accent;
  const { t, lang } = window.useLang();
  const [step, setStep] = useStateQ(0);
  const [done, setDone] = useStateQ(false);
  const [submitting, setSubmitting] = useStateQ(false);
  const [submitError, setSubmitError] = useStateQ(null);
  const [requestId, setRequestId] = useStateQ("");
  const [data, setData] = useStateQ({
    types: [],
    qty: "",
    print: [],
    timeline: "",
    note: "",
    name: "",
    phone: "",
    email: "",
    company: "",
    contactPref: "line",
  });

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

  const can = step === 0 ? data.types.length > 0
    : step === 1 ? data.qty && data.timeline
    : data.name && data.phone;

  const submit = async (e) => {
    e.preventDefault();
    if (!can || submitting) return;
    setSubmitting(true);
    setSubmitError(null);
    try {
      const payload = { lang, ...data, submittedAt: new Date().toISOString() };
      const res = await fetch(QUOTE_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "text/plain;charset=utf-8" },
        body: JSON.stringify(payload),
        redirect: "follow",
      });
      if (!res.ok) throw new Error("HTTP " + res.status);
      const json = await res.json();
      if (!json.ok) throw new Error(json.error || "submit failed");
      setRequestId(json.requestId || "");
      setDone(true);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (err) {
      console.error("Quote submit failed:", err);
      setSubmitError(String(err && err.message ? err.message : err));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div style={{ "--accent": accent }}>
      <window.Grain />
      <window.ScrollProgress accent={accent} />
      <window.CustomCursor accent={accent} />

      {/* Top bar */}
      <nav className="relative z-20 px-6 md:px-10 py-6 flex items-center justify-between border-b border-white/5">
        <a href="Landing Page.html" className="flex items-center gap-3">
          <div className="relative w-9 h-9">
            <div className="absolute inset-0" style={{ background: accent, clipPath: "polygon(0 0, 100% 0, 100% 70%, 70% 100%, 0 100%)" }} />
            <div className="absolute inset-[3px] bg-black flex items-center justify-center font-black text-white text-sm" style={{ clipPath: "polygon(0 0, 100% 0, 100% 70%, 70% 100%, 0 100%)" }}>F</div>
          </div>
          <div className="leading-none">
            <div className="text-white font-black tracking-tight text-lg">FENIX</div>
            <div className="font-mono text-[9px] tracking-[0.3em] text-white/40 mt-0.5">UNIFORM CO.</div>
          </div>
        </a>
        <div className="flex items-center gap-4">
          <window.LangSwitch accent={accent} />
          <a href="Landing Page.html" className="font-mono text-[11px] tracking-[0.2em] uppercase text-white/60 hover:text-white">{t('quote.back')}</a>
        </div>
      </nav>

      {/* Red glow */}
      <div className="fixed -right-40 top-0 w-[600px] h-[600px] rounded-full blur-[140px] opacity-20 pointer-events-none" style={{ background: accent }} />

      <div className="relative max-w-5xl mx-auto px-6 md:px-10 py-12 md:py-16">
        {!done && (
          <>
            {/* Header */}
            <div className="flex flex-wrap items-end justify-between gap-6 mb-12">
              <div>
                <div className="flex items-center gap-3 mb-4">
                  <div className="w-10 h-px" style={{ background: accent }} />
                  <span className="font-mono text-[11px] tracking-[0.3em] uppercase" style={{ color: accent }}>{t('quote.eyebrow')}</span>
                </div>
                <h1 className="text-white font-black leading-[0.95] tracking-tight" style={{ fontSize: "clamp(40px, 6vw, 88px)" }}>
                  {t('quote.headline.l1')}<br />{t('quote.headline.l2')}<span style={{ color: accent }}>.</span>
                </h1>
              </div>
              <div className="text-right">
                <div className="font-mono text-[10px] tracking-[0.25em] text-white/40">{t('quote.responseTime')}</div>
                <div className="text-white font-black text-3xl">{t('quote.responseTimeValue')}</div>
                <div className="font-mono text-[10px] tracking-wider text-white/50 mt-1">{t('quote.responseHours')}</div>
              </div>
            </div>

            <Stepper step={step} accent={accent} />

            <form onSubmit={submit} className="border border-white/10 bg-white/[0.02] p-6 md:p-10">
              {/* STEP 0 - product type */}
              {step === 0 && (
                <window.Reveal>
                  <div>
                    <div className="font-mono text-[10px] tracking-[0.25em] text-white/40 mb-2">{t('quote.questionPrefix')} 01</div>
                    <h2 className="text-white text-3xl md:text-4xl font-black mb-2">{t('quote.q1.title')}</h2>
                    <p className="text-white/50 text-sm mb-8">{t('quote.q1.subtitle')}</p>

                    <div className="grid sm:grid-cols-2 gap-3 mb-2">
                      {PRODUCT_TYPES.map((p) => {
                        const active = data.types.includes(p.key);
                        return (
                          <Choice key={p.key} active={active} onClick={() => toggleArr("types", p.key)} accent={accent}>
                            <div className="flex items-start gap-4">
                              <div className="w-12 h-12 flex items-center justify-center text-2xl font-black shrink-0" style={{ background: active ? accent : "rgba(255,255,255,0.05)", color: active ? "#0a0a0a" : "white" }}>
                                {p.icon}
                              </div>
                              <div className="flex-1">
                                <div className="flex items-center gap-2 mb-1">
                                  <span className="font-mono text-[10px] tracking-wider text-white/40">{p.code}</span>
                                </div>
                                <div className="text-white font-bold text-lg">{t(`quote.types.${p.key}`)}</div>
                                <div className="text-white/50 text-sm">{t(`quote.types.${p.key}.desc`)}</div>
                              </div>
                              <div className="w-5 h-5 border-2 flex items-center justify-center shrink-0" style={{ borderColor: active ? accent : "rgba(255,255,255,0.2)", background: active ? accent : "transparent" }}>
                                {active && <span className="text-black font-black text-xs">✓</span>}
                              </div>
                            </div>
                          </Choice>
                        );
                      })}
                    </div>
                  </div>
                </window.Reveal>
              )}

              {/* STEP 1 - details */}
              {step === 1 && (
                <window.Reveal>
                  <div className="space-y-10">
                    <div>
                      <div className="font-mono text-[10px] tracking-[0.25em] text-white/40 mb-2">{t('quote.questionPrefix')} 02</div>
                      <h2 className="text-white text-2xl md:text-3xl font-black mb-5">{t('quote.q2.title')} <span style={{ color: accent }}>*</span></h2>
                      <div className="flex flex-wrap gap-2">
                        {QTY_RANGES.map((q) => (
                          <button key={q} type="button" onClick={() => update("qty", q)} className="px-5 py-3 border text-sm font-mono tracking-wider transition" style={{ background: data.qty === q ? accent : "transparent", borderColor: data.qty === q ? accent : "rgba(255,255,255,0.15)", color: data.qty === q ? "#0a0a0a" : "white", fontWeight: data.qty === q ? 700 : 500 }}>
                            {q} {t('quote.qty.unit')}
                          </button>
                        ))}
                      </div>
                    </div>

                    <div>
                      <div className="font-mono text-[10px] tracking-[0.25em] text-white/40 mb-2">{t('quote.questionPrefix')} 03</div>
                      <h2 className="text-white text-2xl md:text-3xl font-black mb-2">{t('quote.q3.title')} <span style={{ color: accent }}>*</span></h2>
                      <div className="grid sm:grid-cols-2 gap-3">
                        {TIMELINE_KEYS.map((tk) => (
                          <button key={tk} type="button" onClick={() => update("timeline", tk)} className="text-left p-4 border transition" style={{ background: data.timeline === tk ? `${accent}14` : "transparent", borderColor: data.timeline === tk ? accent : "rgba(255,255,255,0.1)" }}>
                            <div className="text-white font-bold">{t(`quote.timeline.${tk}`)}</div>
                          </button>
                        ))}
                      </div>
                    </div>

                    <div>
                      <div className="font-mono text-[10px] tracking-[0.25em] text-white/40 mb-2">{t('quote.questionPrefix')} 04</div>
                      <h2 className="text-white text-2xl md:text-3xl font-black mb-2">{t('quote.q4.title')}</h2>
                      <p className="text-white/50 text-sm mb-4">{t('quote.q4.subtitle')}</p>
                      <div className="flex flex-wrap gap-2">
                        {PRINT_KEYS.map((pk) => (
                          <button key={pk} type="button" onClick={() => toggleArr("print", pk)} className="px-4 py-2.5 border text-sm font-mono tracking-wider rounded-full transition" style={{ background: data.print.includes(pk) ? accent : "transparent", borderColor: data.print.includes(pk) ? accent : "rgba(255,255,255,0.15)", color: data.print.includes(pk) ? "#0a0a0a" : "white", fontWeight: data.print.includes(pk) ? 700 : 500 }}>
                            {t(`quote.print.${pk}`)}
                          </button>
                        ))}
                      </div>
                    </div>

                    <div>
                      <div className="font-mono text-[10px] tracking-[0.25em] text-white/40 mb-2">{t('quote.questionPrefix')} 05</div>
                      <h2 className="text-white text-2xl md:text-3xl font-black mb-4">{t('quote.q5.title')}</h2>
                      <textarea
                        value={data.note}
                        onChange={(e) => update("note", e.target.value)}
                        rows={5}
                        placeholder={t('quote.q5.placeholder')}
                        className="w-full bg-transparent border border-white/15 px-4 py-3 text-white text-base focus:outline-none focus:border-white transition resize-none"
                      />
                      <div className="font-mono text-[10px] tracking-wider text-white/30 mt-2">
                        {t('quote.q5.tip')}
                      </div>
                    </div>
                  </div>
                </window.Reveal>
              )}

              {/* STEP 2 - contact */}
              {step === 2 && (
                <window.Reveal>
                  <div className="space-y-8">
                    <div>
                      <div className="font-mono text-[10px] tracking-[0.25em] text-white/40 mb-2">{t('quote.questionPrefix')} 06</div>
                      <h2 className="text-white text-2xl md:text-3xl font-black mb-6">{t('quote.q6.title')}</h2>
                      <div className="grid md:grid-cols-2 gap-5">
                        <QField label={t('quote.field.name')} required value={data.name} onChange={(v) => update("name", v)} placeholder={t('quote.field.namePlaceholder')} />
                        <QField label={t('quote.field.phone')} required value={data.phone} onChange={(v) => update("phone", v)} placeholder="08X-XXX-XXXX" type="tel" />
                        <QField label={t('quote.field.email')} value={data.email} onChange={(v) => update("email", v)} placeholder="you@example.com" type="email" />
                        <QField label={t('quote.field.company')} value={data.company} onChange={(v) => update("company", v)} placeholder={t('quote.field.companyPlaceholder')} />
                      </div>
                    </div>

                    <div>
                      <div className="font-mono text-[10px] tracking-[0.25em] text-white/40 mb-3">{t('quote.contactPref.label')}</div>
                      <div className="flex flex-wrap gap-2">
                        {[["line", "quote.contactPref.line"], ["phone", "quote.contactPref.phone"], ["email", "quote.contactPref.email"]].map(([k, lblKey]) => (
                          <button key={k} type="button" onClick={() => update("contactPref", k)} className="px-5 py-2.5 border text-sm font-mono tracking-wider rounded-full transition" style={{ background: data.contactPref === k ? accent : "transparent", borderColor: data.contactPref === k ? accent : "rgba(255,255,255,0.15)", color: data.contactPref === k ? "#0a0a0a" : "white", fontWeight: data.contactPref === k ? 700 : 500 }}>
                            {t(lblKey)}
                          </button>
                        ))}
                      </div>
                    </div>

                    {/* Summary */}
                    <div className="border border-white/10 p-5 bg-black/30">
                      <div className="font-mono text-[10px] tracking-[0.25em] text-white/40 mb-3">{t('quote.summary.title')}</div>
                      <div className="space-y-2 text-sm">
                        <div className="flex gap-3">
                          <span className="text-white/40 w-24 shrink-0">{t('quote.summary.type')}</span>
                          <span className="text-white">{data.types.length ? data.types.map(k => t(`quote.types.${k}`)).join(", ") : t('quote.summary.empty')}</span>
                        </div>
                        <div className="flex gap-3">
                          <span className="text-white/40 w-24 shrink-0">{t('quote.summary.qty')}</span>
                          <span className="text-white">{data.qty ? `${data.qty} ${t('quote.qty.unit')}` : t('quote.summary.empty')}</span>
                        </div>
                        <div className="flex gap-3">
                          <span className="text-white/40 w-24 shrink-0">{t('quote.summary.timeline')}</span>
                          <span className="text-white">{data.timeline ? t(`quote.timeline.${data.timeline}`) : t('quote.summary.empty')}</span>
                        </div>
                        {data.print.length > 0 && (
                          <div className="flex gap-3">
                            <span className="text-white/40 w-24 shrink-0">{t('quote.summary.print')}</span>
                            <span className="text-white">{data.print.map(k => t(`quote.print.${k}`)).join(", ")}</span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </window.Reveal>
              )}

              {/* Error banner */}
              {submitError && (
                <div className="mt-8 border border-red-500/40 bg-red-500/[0.06] p-4 flex items-start gap-3">
                  <div className="w-7 h-7 flex items-center justify-center font-black text-xs shrink-0" style={{ background: accent, color: "#0a0a0a" }}>!</div>
                  <div className="flex-1">
                    <div className="text-white font-bold text-sm">{t('quote.error.title')}</div>
                    <div className="text-white/60 text-sm mt-1">{t('quote.error.body')}</div>
                  </div>
                </div>
              )}

              {/* Nav */}
              <div className="flex items-center justify-between gap-4 mt-12 pt-6 border-t border-white/10">
                <button
                  type="button"
                  onClick={() => setStep((s) => Math.max(0, s - 1))}
                  disabled={step === 0 || submitting}
                  className="px-6 py-3 text-sm font-mono tracking-wider uppercase border border-white/15 text-white hover:border-white transition disabled:opacity-30 disabled:cursor-not-allowed"
                >
                  {t('quote.nav.back')}
                </button>
                <div className="font-mono text-[10px] tracking-[0.25em] text-white/40">
                  {t('quote.step.indicator')} {step + 1} / 3
                </div>
                {step < 2 ? (
                  <button
                    type="button"
                    onClick={() => can && setStep((s) => s + 1)}
                    disabled={!can}
                    className="shine-btn px-7 py-3 text-sm font-bold tracking-wider uppercase text-black transition disabled:opacity-40 disabled:cursor-not-allowed"
                    style={{ background: accent }}
                  >
                    {t('quote.nav.next')}
                  </button>
                ) : (
                  <button
                    type="submit"
                    disabled={!can || submitting}
                    className="shine-btn px-7 py-3 text-sm font-bold tracking-wider uppercase text-black transition disabled:opacity-40 disabled:cursor-not-allowed inline-flex items-center gap-2"
                    style={{ background: accent }}
                  >
                    {submitting && (
                      <span
                        className="inline-block w-3.5 h-3.5 border-2 border-black/30 border-t-black rounded-full animate-spin"
                        aria-hidden="true"
                      />
                    )}
                    {submitting ? t('quote.nav.sending') : (submitError ? t('quote.error.retry') : t('quote.nav.submit'))}
                  </button>
                )}
              </div>
            </form>

            {/* Reassurance footer */}
            <div className="grid sm:grid-cols-3 gap-px bg-white/10 mt-px">
              {[
                { lblKey: "quote.foot.free.label", bodyKey: "quote.foot.free.body" },
                { lblKey: "quote.foot.secure.label", bodyKey: "quote.foot.secure.body" },
                { lblKey: "quote.foot.fast.label", bodyKey: "quote.foot.fast.body" },
              ].map((row) => (
                <div key={row.lblKey} className="bg-[#0a0a0a] p-5 flex items-center gap-3">
                  <div className="w-8 h-8 flex items-center justify-center text-[10px] font-black" style={{ background: accent, color: "#0a0a0a" }}>✓</div>
                  <div>
                    <div className="font-mono text-[10px] tracking-[0.2em] text-white/40">{t(row.lblKey)}</div>
                    <div className="text-white text-sm font-medium">{t(row.bodyKey)}</div>
                  </div>
                </div>
              ))}
            </div>
          </>
        )}

        {/* SUCCESS */}
        {done && (
          <window.Reveal>
            <div className="text-center py-16">
              <div className="inline-flex items-center justify-center w-24 h-24 mb-8" style={{ background: accent, color: "#0a0a0a" }}>
                <span className="font-black text-5xl">✓</span>
              </div>
              <div className="flex items-center justify-center gap-3 mb-6">
                <div className="w-10 h-px" style={{ background: accent }} />
                <span className="font-mono text-[11px] tracking-[0.3em] uppercase" style={{ color: accent }}>{t('quote.success.eyebrow')}{requestId ? ` · #${requestId}` : ''}</span>
                <div className="w-10 h-px" style={{ background: accent }} />
              </div>
              <h1 className="text-white font-black leading-[0.95] tracking-tight mb-6" style={{ fontSize: "clamp(40px, 6vw, 88px)" }}>
                {t('quote.success.headline')}<span style={{ color: accent }}>.</span>
              </h1>
              <p className="text-white/60 text-lg max-w-xl mx-auto mb-10 leading-relaxed">
                {t('quote.success.thanks.prefix')}<span className="text-white font-bold">{data.name}</span>{t('quote.success.thanks.suffix')}<br />
                {t('quote.success.message.prefix')}<span className="text-white font-bold">{t(`quote.contactPref.${data.contactPref}`)}</span>{t('quote.success.message.suffix')}
              </p>
              <div className="flex flex-wrap gap-3 justify-center">
                <a href="Landing Page.html" className="px-7 py-3.5 border border-white/20 text-sm font-bold tracking-wider uppercase text-white hover:border-white transition">
                  {t('quote.success.backHome')}
                </a>
                <a href="#" className="shine-btn px-7 py-3.5 text-sm font-bold tracking-wider uppercase text-black" style={{ background: accent }}>
                  {t('quote.success.lineNow')}
                </a>
              </div>
            </div>
          </window.Reveal>
        )}
      </div>

      {/* Footer */}
      <footer className="border-t border-white/10 px-10 py-8 mt-16" style={{ background: "#080808" }}>
        <div className="max-w-5xl mx-auto flex flex-wrap items-center justify-between gap-3 font-mono text-[10px] tracking-wider text-white/40">
          <div>© 2026 FENIX UNIFORM CO., LTD.</div>
          <div className="flex items-center gap-2">
            <span className="w-1.5 h-1.5 rounded-full" style={{ background: accent }} />
            BUILT TO PERFORM
          </div>
        </div>
      </footer>

      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Brand">
          <window.TweakColor
            label="Accent"
            value={tw.accent}
            onChange={(v) => setTweak("accent", v)}
            options={["#E63329", "#FF3B30", "#DC2626", "#FF6B00", "#FACC15", "#22C55E"]}
          />
        </window.TweakSection>
      </window.TweaksPanel>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<QuoteApp />);
