/* global React, SiteHeader, HeroBg, Footer, Reveal, Icon, SHexLogo */
const { useState: useStateC2 } = React;

// ============================================================
// CONTACT PAGE — variant-aware (group | consult | capital)
// ============================================================
const CONTACT_VARIANTS = {
  group: {
    theme: "group",
    eyebrow: "Sinux Group · Holding Company",
    title: "Let's build the future together.",
    sub: "From technology consulting to strategic investment — reach the Sinux Group leadership directly.",
    email: "info@sinuxgroup.com",
    phone: "+60 12-618 7256",
    phoneTel: "+60126187256",
    phoneAlt: "+1 (229) 374-6725",
    phoneAltTel: "+12293746725",
    hours: "Mon–Fri · 10:00am – 9:00pm MYT",
    location: "Kuala Lumpur, Malaysia",
    locationDetail: "Serving clients globally",
    services: [
      "General Inquiry",
      "Partnership / M&A",
      "Investment / Venture",
      "Press & Media",
      "Other",
    ],
    cta: "Send Message",
    footerVariant: "group",
  },
  consult: {
    theme: "consult",
    eyebrow: "Sinux Consulting · Get In Touch",
    title: "Start your next project with us.",
    sub: "Whether you need a subscription website, a full technology platform, or an AI-powered growth strategy — let's talk.",
    email: "info@sinuxconsulting.com",
    phone: "+60 12-618 7256",
    phoneTel: "+60126187256",
    phoneAlt: "+1 (229) 374-6725",
    phoneAltTel: "+12293746725",
    hours: "Mon–Fri · 10:00am – 9:00pm MYT",
    location: "Kuala Lumpur, Malaysia",
    locationDetail: "Serving clients in MY, US, and globally",
    services: [
      "Digital Growth — Websites",
      "Tech Consulting — Advisory",
      "Tech Consulting — MVP / POC",
      "Tech Consulting — Full Suite",
      "ReviewFlow Inquiry",
      "General Inquiry",
    ],
    cta: "Start Your Project",
    footerVariant: "consult",
  },
  capital: {
    theme: "capital",
    eyebrow: "Sinux Capital · Private Mode",
    title: "Strategic capital. Private inquiries.",
    sub: "For partnership inquiries, co-investment opportunities, or business acquisition discussions, reach out directly to Sinux Capital.",
    email: "info@sinuxcapital.com",
    phone: "+60 12-618 7256",
    phoneTel: "+60126187256",
    phoneAlt: "+1 (229) 374-6725",
    phoneAltTel: "+12293746725",
    hours: "By appointment",
    location: "Kuala Lumpur, Malaysia",
    locationDetail: "Private engagement worldwide",
    services: [
      "Co-investment Opportunity",
      "Business Acquisition",
      "Strategic Partnership",
      "Trading / Portfolio Inquiry",
      "Other",
    ],
    cta: "Submit Inquiry",
    footerVariant: "consult", // Sinux Capital footer reuses subsidiary tone
  },
};

function ContactPage({ variant = "group" }) {
  const v = CONTACT_VARIANTS[variant] || CONTACT_VARIANTS.group;
  const [status, setStatus] = useStateC2("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = useStateC2("");

  async function handleSubmit(e) {
    e.preventDefault();
    if (status === "sending") return;
    setStatus("sending");
    setErrorMsg("");

    const form = e.target;
    const fd = new FormData(form);
    const payload = { variant };
    fd.forEach((val, key) => { payload[key] = val; });

    try {
      const r = await fetch("/api/send-email", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!r.ok) {
        const data = await r.json().catch(() => ({}));
        throw new Error(data.error || `Server returned ${r.status}`);
      }
      setStatus("sent");
      form.reset();
    } catch (err) {
      console.warn("[contact form] submit failed", err, payload);
      setStatus("error");
      setErrorMsg(
        err.message?.includes("Failed to fetch")
          ? "Couldn't reach the server. In local preview, the form needs to be deployed to Vercel first."
          : err.message || "Something went wrong. Please email us directly."
      );
    }
  }

  const sent = status === "sent";

  return (
    <div className={`page-enter theme-${v.theme}`} data-screen-label={`Contact · ${variant}`}>
      <SiteHeader current="contact" theme={v.theme} />

      {/* HERO */}
      <section className="hero" data-screen-label="01 Contact Hero" style={{ minHeight: "min(80svh, 700px)" }}>
        <HeroBg theme={v.theme} />
        <div className="container hero-content">
          <Reveal>
            <span className="eyebrow">{v.eyebrow}</span>
          </Reveal>
          <Reveal delay={120}>
            <h1 className="h1" style={{ marginTop: 24, marginBottom: 24, maxWidth: "18ch", fontSize: "clamp(32px, 6.5vw, 88px)" }}>
              {v.title}
            </h1>
          </Reveal>
          <Reveal delay={220}>
            <p className="lede" style={{ maxWidth: 640 }}>{v.sub}</p>
          </Reveal>
        </div>
      </section>

      {/* CONTACT BODY */}
      <section className="section-py" data-screen-label="02 Contact Body" style={{ paddingTop: 0 }}>
        <div className="container">
          <div style={{
            display: "grid",
            gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.4fr)",
            gap: "clamp(32px, 5vw, 80px)",
            alignItems: "start",
          }} className="contact-grid-page">

            {/* LEFT: Info column */}
            <Reveal>
              <div style={{ position: "sticky", top: 100 }} className="contact-info">
                <SHexLogo size={48} variant={v.theme === "capital" ? "capital" : v.theme === "consult" ? "consult" : "group"} />
                <h2 className="h3" style={{ marginTop: 22, marginBottom: 16, fontSize: "clamp(22px,2.4vw,30px)" }}>
                  Reach us directly.
                </h2>
                <p className="text-muted" style={{ marginBottom: 32, fontSize: 14, lineHeight: 1.65 }}>
                  We respond to every inquiry within one business day.
                </p>

                <InfoRow label="Email" accent>
                  <a href={`mailto:${v.email}`} style={{ color: "inherit", textDecoration: "none" }}>{v.email}</a>
                </InfoRow>
                <InfoRow label="Malaysia">
                  <a href={`tel:${v.phoneTel}`} style={{ color: "inherit", textDecoration: "none" }}>{v.phone}</a>
                </InfoRow>
                <InfoRow label="USA">
                  <a href={`tel:${v.phoneAltTel}`} style={{ color: "inherit", textDecoration: "none" }}>{v.phoneAlt}</a>
                </InfoRow>
                <InfoRow label="Hours">{v.hours}</InfoRow>
                <InfoRow label="Office">
                  <div>{v.location}</div>
                  <div style={{ color: "var(--ink-3)", fontSize: 13, marginTop: 4 }}>{v.locationDetail}</div>
                </InfoRow>

                <div style={{ marginTop: 28, paddingTop: 24, borderTop: "1px solid var(--line-2)" }}>
                  <div className="footer-h">Other channels</div>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 14 }}>
                    <a
                      href={`https://wa.me/${v.phoneTel.replace(/\D/g, "")}`}
                      target="_blank"
                      rel="noreferrer"
                      className="btn btn-ghost"
                      style={{ padding: "10px 18px", fontSize: 12 }}
                    >
                      <Icon.whatsapp /> WhatsApp
                    </a>
                    <a
                      href="https://www.linkedin.com/company/sinuxindustries/"
                      target="_blank"
                      rel="noreferrer"
                      className="btn btn-ghost"
                      style={{ padding: "10px 18px", fontSize: 12 }}
                    >
                      <Icon.in /> LinkedIn
                    </a>
                  </div>
                </div>
              </div>
            </Reveal>

            {/* RIGHT: Form */}
            <Reveal delay={120}>
              <form
                className="card elevated"
                onSubmit={handleSubmit}
                style={{ padding: "clamp(28px, 4vw, 48px)" }}
              >
                {/* honeypot — silently drops bots */}
                <input type="text" name="_hp" tabIndex="-1" autoComplete="off" style={{ position: "absolute", left: "-9999px", width: 1, height: 1 }} aria-hidden="true" />
                {!sent ? (
                  <>
                    <h2 className="h3" style={{ marginBottom: 8, fontSize: "clamp(22px,2.4vw,30px)" }}>
                      Tell us about your project.
                    </h2>
                    <p className="text-muted" style={{ marginBottom: 32, fontSize: 14, lineHeight: 1.6 }}>
                      The more detail, the faster we can connect you to the right person on the team.
                    </p>

                    <div className="auto-grid" style={{ "--min": "200px", gap: 20 }}>
                      <div className="field">
                        <label>Your name</label>
                        <input name="name" required placeholder="Full name" />
                      </div>
                      <div className="field">
                        <label>Email</label>
                        <input name="email" required type="email" placeholder="you@company.com" />
                      </div>
                    </div>

                    <div className="auto-grid" style={{ "--min": "200px", gap: 20, marginTop: 20 }}>
                      <div className="field">
                        <label>Phone (optional)</label>
                        <input name="phone" type="tel" placeholder="+60 …" />
                      </div>
                      <div className="field">
                        <label>Company / Organization</label>
                        <input name="company" placeholder="Your company" />
                      </div>
                    </div>

                    <div className="field" style={{ marginTop: 20 }}>
                      <label>Inquiry type</label>
                      <select name="inquiryType" required defaultValue="">
                        <option value="" disabled>Select an option…</option>
                        {v.services.map((s) => <option key={s}>{s}</option>)}
                      </select>
                    </div>

                    {variant === "consult" && (
                      <div className="auto-grid" style={{ "--min": "200px", gap: 20, marginTop: 20 }}>
                        <div className="field">
                          <label>Estimated budget</label>
                          <select name="budget" defaultValue="">
                            <option value="" disabled>Select range…</option>
                            <option>Subscription · $299–499/mo</option>
                            <option>Signature Build · $3k–10k</option>
                            <option>MVP · $10k–30k</option>
                            <option>Full Suite · $30k+</option>
                            <option>Not sure yet</option>
                          </select>
                        </div>
                        <div className="field">
                          <label>Timeline</label>
                          <select name="timeline" defaultValue="">
                            <option value="" disabled>Select…</option>
                            <option>Immediate</option>
                            <option>1–3 months</option>
                            <option>3–6 months</option>
                            <option>Exploratory</option>
                          </select>
                        </div>
                      </div>
                    )}

                    <div className="field" style={{ marginTop: 20 }}>
                      <label>Tell us more</label>
                      <textarea name="message" required rows="6" placeholder="Project goals, timeline, audience, any specifics we should know…" />
                    </div>

                    {status === "error" && (
                      <div style={{
                        marginTop: 20, padding: "12px 16px",
                        background: "rgba(220, 38, 38, 0.08)",
                        border: "1px solid rgba(220, 38, 38, 0.3)",
                        borderRadius: 10,
                        color: "#fca5a5",
                        fontSize: 13,
                        lineHeight: 1.5,
                      }}>
                        <strong style={{ color: "#fecaca" }}>Couldn't send:</strong> {errorMsg}
                        {" "}You can email us directly at{" "}
                        <a href={`mailto:${v.email}`} style={{ color: "#fecaca", textDecoration: "underline" }}>{v.email}</a>.
                      </div>
                    )}

                    <div style={{ marginTop: 24, display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap", justifyContent: "space-between" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--ink-3)" }}>
                        <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#2dd4a4" }} />
                        Avg. response time: under 24 hours
                      </div>
                      <button
                        type="submit"
                        className="btn btn-primary"
                        disabled={status === "sending"}
                        style={status === "sending" ? { opacity: 0.6, cursor: "wait" } : {}}
                      >
                        {status === "sending" ? "Sending…" : v.cta}
                        {status !== "sending" && <Icon.arrow className="arrow" />}
                      </button>
                    </div>

                    <div style={{ marginTop: 24, fontSize: 11, color: "var(--ink-4)", lineHeight: 1.6 }}>
                      By submitting this form, you agree to our{" "}
                      <a href="/privacy" style={{ color: "var(--accent)" }}>Privacy Policy</a>{" "}
                      and{" "}
                      <a href="/terms" style={{ color: "var(--accent)" }}>Terms & Conditions</a>.
                    </div>
                  </>
                ) : (
                  <SentConfirmation v={v} onReset={() => setStatus("idle")} />
                )}
              </form>
            </Reveal>
          </div>
        </div>
      </section>

      {/* OTHER DIVISIONS */}
      <section className="section-py" data-screen-label="03 Other Divisions" style={{ borderTop: "1px solid var(--line-2)", background: "rgba(255,255,255,0.015)" }}>
        <div className="container">
          <Reveal>
            <span className="eyebrow">Looking for another division?</span>
            <h2 className="h2" style={{ marginTop: 16, marginBottom: 14, maxWidth: "22ch", fontSize: "clamp(24px,4vw,44px)" }}>
              Contact the right team directly.
            </h2>
          </Reveal>
          <div className="auto-grid" style={{ "--min": "280px", marginTop: 40, gap: "var(--gap-md)" }}>
            {[
              { id: "group", variant: "group", title: "Sinux Group", email: "info@sinuxgroup.com", desc: "Holding company, leadership, partnerships.", href: "#/contact" },
              { id: "consult", variant: "consult", title: "Sinux Consulting", email: "info@sinuxconsulting.com", desc: "Technology consulting & digital growth.", href: "#/consulting/contact" },
              { id: "capital", variant: "capital", title: "Sinux Capital", email: "info@sinuxcapital.com", desc: "Investments, ventures, acquisitions.", href: "#/capital/contact" },
            ].filter(d => d.id !== variant).map((d) => (
              <Reveal key={d.id}>
                <a href={d.href} className={`card theme-${d.variant}`} style={{ display: "block", textDecoration: "none", color: "inherit", height: "100%" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                    <SHexLogo size={36} variant={d.variant} />
                    <Icon.arrow style={{ color: "var(--accent)" }} />
                  </div>
                  <h4 className="h4" style={{ marginTop: 20, marginBottom: 6 }}>{d.title}</h4>
                  <div style={{ color: "var(--accent)", fontSize: 13, marginBottom: 12, letterSpacing: "0.02em" }}>{d.email}</div>
                  <p style={{ color: "var(--ink-2)", fontSize: 13, lineHeight: 1.6 }}>{d.desc}</p>
                </a>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      <Footer variant={v.footerVariant} />
    </div>
  );
}

function InfoRow({ label, children, accent }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "100px 1fr",
      gap: 16,
      padding: "14px 0",
      borderBottom: "1px solid var(--line-2)",
      alignItems: "start",
    }}>
      <div style={{
        fontSize: 11,
        letterSpacing: "0.14em",
        textTransform: "uppercase",
        color: "var(--ink-3)",
        fontFamily: "'Michroma',sans-serif",
        paddingTop: 2,
      }}>{label}</div>
      <div style={{ color: accent ? "var(--accent)" : "var(--ink)", fontSize: 15, lineHeight: 1.5, wordBreak: "break-word" }}>
        {children}
      </div>
    </div>
  );
}

function SentConfirmation({ v, onReset }) {
  return (
    <div style={{ textAlign: "center", padding: "clamp(20px,3vw,40px) 0" }}>
      <div style={{
        width: 72, height: 72, borderRadius: "50%",
        background: "color-mix(in oklab, var(--accent) 18%, transparent)",
        border: "1px solid color-mix(in oklab, var(--accent) 40%, transparent)",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        marginBottom: 24,
      }}>
        <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2"><path d="M4 12l5 5L20 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </div>
      <h3 className="h3" style={{ marginBottom: 14, fontSize: "clamp(22px,2.6vw,30px)" }}>Message received.</h3>
      <p className="text-muted" style={{ maxWidth: 480, marginInline: "auto", marginBottom: 28, fontSize: 14, lineHeight: 1.65 }}>
        Thank you — we'll be in touch within one business day at the email address you provided.
        For urgent matters, reach us directly at{" "}
        <a href={`mailto:${v.email}`} style={{ color: "var(--accent)" }}>{v.email}</a>.
      </p>
      <button onClick={onReset} className="btn btn-ghost">Send another message</button>
    </div>
  );
}

window.ContactPage = ContactPage;
window.CONTACT_VARIANTS = CONTACT_VARIANTS;
