const { useState, useEffect } = React;

// ===== Supabase client =====
const SB_CONFIG = window.__TADPOLE_SUPABASE__ || {};
const supabase = window.supabase.createClient(SB_CONFIG.url, SB_CONFIG.anonKey, {
  auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false }
});

// ===== Constants =====
const HEADLINE = "AI talent and client intelligence for modern accounting firms.";
const CTA_LABEL = "Join waitlist";

const FIRM_SIZES = [
  { v: "",        l: "Select…" },
  { v: "1-10",    l: "1–10" },
  { v: "11-50",   l: "11–50" },
  { v: "51-100",  l: "51–100" },
  { v: "101-200", l: "101–200" },
  { v: "200+",    l: "200+" }
];

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// ===== Logo / wordmark =====
function Logo({ size = 28 }) {
  return (
    <img
      src="tadpole_logo.png"
      width={size}
      height={size}
      alt="Tadpole"
      style={{ display: "block", objectFit: "contain" }}
    />
  );
}

function Wordmark({ size = 22 }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9, color: "var(--ink)" }}>
      <Logo size={size + 6} />
      <span style={{ fontSize: size, fontWeight: 800, letterSpacing: "-0.02em" }}>Tadpole</span>
    </div>
  );
}

// ===== Header =====
function Header() {
  return (
    <header
      style={{
        position: "sticky",
        top: 0,
        zIndex: 10,
        background: "rgba(247,248,250,0.85)",
        backdropFilter: "saturate(180%) blur(12px)",
        WebkitBackdropFilter: "saturate(180%) blur(12px)",
        borderBottom: "1px solid var(--line-2)"
      }}
    >
      <div
        style={{
          maxWidth: 1200,
          margin: "0 auto",
          padding: "16px 24px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between"
        }}
      >
        <Wordmark />
      </div>
    </header>
  );
}

// ===== Video placeholder =====
function VideoPlayer() {
  const [playing, setPlaying] = useState(false);
  return (
    <div
      onClick={() => setPlaying((p) => !p)}
      style={{
        position: "relative",
        width: "100%",
        aspectRatio: "16 / 10",
        borderRadius: 18,
        overflow: "hidden",
        background:
          "radial-gradient(120% 90% at 20% 10%, #2B2F70 0%, #15173A 55%, #0B0D24 100%)",
        boxShadow:
          "0 1px 0 rgba(255,255,255,0.6) inset, 0 30px 60px -20px rgba(15,18,34,0.35), 0 12px 24px -12px rgba(15,18,34,0.2)",
        cursor: "pointer",
        border: "1px solid rgba(255,255,255,0.08)"
      }}
    >
      <div
        aria-hidden
        style={{
          position: "absolute",
          inset: 0,
          opacity: 0.18,
          backgroundImage:
            "repeating-linear-gradient(0deg, rgba(255,255,255,0.06) 0 1px, transparent 1px 28px), repeating-linear-gradient(90deg, rgba(255,255,255,0.06) 0 1px, transparent 1px 28px)"
        }}
      />
      <div
        aria-hidden
        style={{
          position: "absolute",
          left: "8%",
          top: "12%",
          right: "8%",
          bottom: "18%",
          borderRadius: 10,
          background: "rgba(255,255,255,0.04)",
          border: "1px solid rgba(255,255,255,0.08)",
          display: "grid",
          gridTemplateColumns: "120px 1fr"
        }}
      >
        <div style={{ borderRight: "1px solid rgba(255,255,255,0.06)", padding: 12 }}>
          {["Scorecards", "Coaching", "Feedback", "Profitability"].map((l, i) => (
            <div
              key={l}
              style={{
                fontSize: 9,
                color: i === 0 ? "#fff" : "rgba(255,255,255,0.4)",
                background: i === 0 ? "rgba(91,95,233,0.25)" : "transparent",
                padding: "4px 6px",
                borderRadius: 4,
                marginBottom: 4
              }}
            >
              {l}
            </div>
          ))}
        </div>
        <div style={{ padding: 12 }}>
          <div
            style={{
              fontSize: 11,
              color: "#fff",
              fontWeight: 700,
              marginBottom: 8,
              letterSpacing: "-0.01em"
            }}
          >
            Scorecards
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "60px repeat(7, 1fr)",
              gap: 3,
              fontSize: 7,
              color: "rgba(255,255,255,0.6)"
            }}
          >
            {["", "NOV", "DEC", "JAN", "FEB", "MAR", "APR", "MAY"].map((h) => (
              <div key={h} style={{ padding: 3 }}>{h}</div>
            ))}
            {["Revenue", "GPM", "A/R 60d"].map((r, ri) => (
              <React.Fragment key={r}>
                <div style={{ padding: 3, color: "rgba(255,255,255,0.85)" }}>{r}</div>
                {[0, 1, 2, 3, 4, 5, 6].map((c) => {
                  const tone =
                    ri === 0
                      ? "rgba(244,114,114,0.18)"
                      : ri === 1
                      ? "rgba(108,214,148,0.18)"
                      : c > 3
                      ? "rgba(244,114,114,0.18)"
                      : "rgba(108,214,148,0.18)";
                  return <div key={c} style={{ height: 14, background: tone, borderRadius: 2 }} />;
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>

      <div
        style={{
          position: "absolute",
          inset: 0,
          display: "flex",
          alignItems: "center",
          justifyContent: "center"
        }}
      >
        <div
          style={{
            width: 84,
            height: 84,
            borderRadius: 999,
            background: "rgba(255,255,255,0.95)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            boxShadow: "0 12px 30px rgba(0,0,0,0.35), 0 0 0 8px rgba(255,255,255,0.12)",
            transform: playing ? "scale(0.9)" : "scale(1)",
            transition: "transform 200ms ease"
          }}
        >
          {playing ? (
            <div style={{ display: "flex", gap: 6 }}>
              <div style={{ width: 6, height: 26, background: "#15173A", borderRadius: 2 }} />
              <div style={{ width: 6, height: 26, background: "#15173A", borderRadius: 2 }} />
            </div>
          ) : (
            <div
              style={{
                width: 0,
                height: 0,
                borderTop: "14px solid transparent",
                borderBottom: "14px solid transparent",
                borderLeft: "22px solid #15173A",
                marginLeft: 6
              }}
            />
          )}
        </div>
      </div>

      <div
        style={{
          position: "absolute",
          left: 18,
          bottom: 14,
          display: "flex",
          alignItems: "center",
          gap: 10,
          color: "#fff"
        }}
      >
        <div
          style={{
            width: 8,
            height: 8,
            borderRadius: 999,
            background: "#FF5C5C",
            boxShadow: "0 0 0 3px rgba(255,92,92,0.25)"
          }}
        />
        <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.02em" }}>
          {playing ? "PLAYING DEMO" : "WATCH 2-MIN DEMO"}
        </span>
      </div>
      <div
        style={{
          position: "absolute",
          right: 18,
          bottom: 14,
          color: "rgba(255,255,255,0.6)",
          fontSize: 12,
          fontWeight: 500
        }}
      >
        2:14
      </div>
    </div>
  );
}

// ===== Form =====
function WaitlistForm() {
  const [state, setState] = useState({ name: "", email: "", firm: "", size: "" });
  const [touched, setTouched] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [serverError, setServerError] = useState("");
  const [submittedSnapshot, setSubmittedSnapshot] = useState(null);

  const update = (k) => (e) => {
    // Hard cap input lengths client-side. The DB enforces the same caps as a
    // backstop, so this is purely UX — keeps the field from looking bonkers.
    const max = k === "email" ? 254 : k === "firm" ? 200 : k === "name" ? 120 : 64;
    const v = (e.target.value || "").slice(0, max);
    setState((s) => ({ ...s, [k]: v }));
  };
  const blur = (k) => () => setTouched((t) => ({ ...t, [k]: true }));

  const errors = {
    name: !state.name.trim() && touched.name ? "Please enter your name" : "",
    email: !state.email.trim()
      ? touched.email ? "Work email required" : ""
      : !EMAIL_RE.test(state.email) ? "Enter a valid email" : "",
    firm: !state.firm.trim() && touched.firm ? "Please enter your firm" : ""
  };

  const canSubmit =
    state.name.trim() && EMAIL_RE.test(state.email) && state.firm.trim() && !submitting;

  const onSubmit = async (e) => {
    e.preventDefault();
    setTouched({ name: true, email: true, firm: true });
    setServerError("");
    if (!state.name.trim() || !EMAIL_RE.test(state.email) || !state.firm.trim()) return;

    setSubmitting(true);
    const payload = {
      name: state.name.trim(),
      email: state.email.trim().toLowerCase(),
      firm: state.firm.trim(),
      firm_size: state.size || null,
      source: SB_CONFIG.source || null,
      user_agent: (navigator.userAgent || "").slice(0, 512)
    };

    const { error } = await supabase
      .from(SB_CONFIG.table || "waitlist_signups")
      .insert(payload);

    setSubmitting(false);

    if (error) {
      // 23505 = unique_violation (duplicate email). Treat as success — the
      // visitor is already on the list, no reason to make them feel rejected.
      if (error.code === "23505") {
        setSubmittedSnapshot(payload);
        setSubmitted(true);
        return;
      }
      console.error("waitlist insert failed", error);
      setServerError("Something went wrong on our end. Please try again in a moment.");
      return;
    }

    setSubmittedSnapshot(payload);
    setSubmitted(true);

    // Best-effort analytics hook — only fires if you've wired one in.
    if (typeof window.gtag === "function") {
      window.gtag("event", "waitlist_submit_succeeded", { firm_size: payload.firm_size || "unspecified" });
    }
  };

  if (submitted && submittedSnapshot) {
    return (
      <div
        style={{
          background: "var(--bg-card)",
          border: "1px solid var(--line)",
          borderRadius: 20,
          padding: "40px 32px",
          boxShadow: "0 1px 0 rgba(0,0,0,0.02), 0 20px 40px -20px rgba(15,18,34,0.10)",
          textAlign: "center"
        }}
      >
        <div
          style={{
            width: 60,
            height: 60,
            borderRadius: 999,
            background: "var(--green-50)",
            color: "var(--green-700)",
            margin: "0 auto 16px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center"
          }}
        >
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none">
            <path
              d="M5 12.5l4.5 4.5L19 7.5"
              stroke="currentColor"
              strokeWidth="3"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </div>
        <h3 style={{ margin: "0 0 8px", fontSize: 24, letterSpacing: "-0.02em", fontWeight: 800 }}>
          You're on the list.
        </h3>
        <p
          style={{
            margin: "0 0 18px",
            color: "var(--ink-3)",
            fontSize: 15,
            lineHeight: 1.55,
            maxWidth: 360,
            marginInline: "auto"
          }}
        >
          We'll be in touch at{" "}
          <strong style={{ color: "var(--ink-2)" }}>{submittedSnapshot.email}</strong>{" "}
          with details about early access when a spot opens up for {submittedSnapshot.firm}.
        </p>
        <p
          style={{
            margin: "0 0 18px",
            color: "var(--ink-3)",
            fontSize: 15,
            lineHeight: 1.55,
            maxWidth: 360,
            marginInline: "auto"
          }}
        >
          Email us at{" "}
          <a
            href="mailto:team@tadpoleapp.ai"
            style={{ color: "var(--indigo)", fontWeight: 700, textDecoration: "none" }}
          >
            team@tadpoleapp.ai
          </a>{" "}
          to schedule a demo!
        </p>
      </div>
    );
  }

  return (
    <form
      onSubmit={onSubmit}
      noValidate
      style={{
        background: "var(--bg-card)",
        border: "1px solid var(--line)",
        borderRadius: 20,
        padding: 28,
        boxShadow: "0 1px 0 rgba(0,0,0,0.02), 0 20px 40px -20px rgba(15,18,34,0.10)"
      }}
    >
      <div style={{ marginBottom: 22 }}>
        <h2 style={{ margin: 0, fontSize: 22, letterSpacing: "-0.02em", fontWeight: 800 }}>
          Join the waitlist for early access
        </h2>
      </div>

      <div style={{ display: "grid", gap: 14 }}>
        <Field
          label="Full name"
          value={state.name}
          onChange={update("name")}
          onBlur={blur("name")}
          error={errors.name}
          placeholder="Jane Whitman"
          autoComplete="name"
          maxLength={120}
        />
        <Field
          label="Work email"
          type="email"
          value={state.email}
          onChange={update("email")}
          onBlur={blur("email")}
          error={errors.email}
          placeholder="jane@whitmancpa.com"
          autoComplete="email"
          maxLength={254}
          inputMode="email"
        />
        <Field
          label="Firm"
          value={state.firm}
          onChange={update("firm")}
          onBlur={blur("firm")}
          error={errors.firm}
          placeholder="Whitman & Co."
          autoComplete="organization"
          maxLength={200}
        />
        <SelectField
          label="Firm size"
          value={state.size}
          onChange={update("size")}
          options={FIRM_SIZES}
        />
      </div>

      <button
        type="submit"
        disabled={submitting}
        style={{
          marginTop: 22,
          width: "100%",
          padding: "16px 20px",
          background: "var(--indigo)",
          color: "#fff",
          border: "none",
          borderRadius: 12,
          fontSize: 16,
          fontWeight: 700,
          letterSpacing: "-0.01em",
          cursor: submitting ? "wait" : "pointer",
          opacity: submitting ? 0.85 : 1,
          boxShadow: "0 1px 0 rgba(255,255,255,0.2) inset, 0 6px 14px -6px rgba(91,95,233,0.5)",
          transition: "transform 80ms ease, background 120ms ease, opacity 120ms ease"
        }}
        onMouseDown={(e) => (e.currentTarget.style.transform = "scale(0.99)")}
        onMouseUp={(e) => (e.currentTarget.style.transform = "scale(1)")}
        onMouseLeave={(e) => (e.currentTarget.style.transform = "scale(1)")}
      >
        {submitting ? "Submitting…" : CTA_LABEL}
      </button>

      {serverError && (
        <p
          role="alert"
          style={{
            margin: "12px 0 0",
            color: "#D03A3A",
            fontSize: 13,
            textAlign: "center",
            lineHeight: 1.5
          }}
        >
          {serverError}
        </p>
      )}

      <p
        style={{
          margin: "14px 0 0",
          color: "var(--ink-3)",
          fontSize: 12,
          textAlign: "center",
          lineHeight: 1.5
        }}
      >
        We'll reach out about early access.
      </p>
    </form>
  );
}

function Field({ label, error, ...rest }) {
  return (
    <label style={{ display: "block" }}>
      <div
        style={{
          fontSize: 13,
          fontWeight: 600,
          color: "var(--ink-2)",
          marginBottom: 6,
          display: "flex",
          justifyContent: "space-between"
        }}
      >
        <span>{label}</span>
        {error && <span style={{ color: "#D03A3A", fontWeight: 500 }}>{error}</span>}
      </div>
      <input
        {...rest}
        style={{
          width: "100%",
          padding: "12px 14px",
          borderRadius: 10,
          border: `1px solid ${error ? "#E59B9B" : "var(--line)"}`,
          background: "#fff",
          fontSize: 15,
          color: "var(--ink)",
          outline: "none",
          transition: "border-color 120ms ease, box-shadow 120ms ease"
        }}
        onFocus={(e) => {
          e.target.style.borderColor = "var(--indigo)";
          e.target.style.boxShadow = "0 0 0 4px rgba(91,95,233,0.15)";
        }}
        onBlurCapture={(e) => {
          e.target.style.borderColor = error ? "#E59B9B" : "var(--line)";
          e.target.style.boxShadow = "none";
        }}
      />
    </label>
  );
}

function SelectField({ label, value, onChange, options }) {
  return (
    <label style={{ display: "block" }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink-2)", marginBottom: 6 }}>
        {label}
      </div>
      <div style={{ position: "relative" }}>
        <select
          value={value}
          onChange={onChange}
          style={{
            width: "100%",
            padding: "12px 36px 12px 14px",
            borderRadius: 10,
            border: "1px solid var(--line)",
            background: "#fff",
            fontSize: 15,
            color: value ? "var(--ink)" : "var(--ink-3)",
            outline: "none",
            appearance: "none",
            cursor: "pointer"
          }}
          onFocus={(e) => {
            e.target.style.borderColor = "var(--indigo)";
            e.target.style.boxShadow = "0 0 0 4px rgba(91,95,233,0.15)";
          }}
          onBlur={(e) => {
            e.target.style.borderColor = "var(--line)";
            e.target.style.boxShadow = "none";
          }}
        >
          {options.map((o) => (
            <option key={o.v} value={o.v}>{o.l}</option>
          ))}
        </select>
        <svg
          width="14"
          height="14"
          viewBox="0 0 16 16"
          style={{
            position: "absolute",
            right: 12,
            top: "50%",
            transform: "translateY(-50%)",
            pointerEvents: "none",
            color: "var(--ink-3)"
          }}
          fill="none"
        >
          <path
            d="M4 6l4 4 4-4"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      </div>
    </label>
  );
}

// ===== Hero =====
function Hero() {
  return (
    <section style={{ maxWidth: 1200, margin: "0 auto", padding: "48px 24px 32px" }}>
      <h1
        style={{
          margin: 0,
          fontSize: "clamp(36px, 5.4vw, 60px)",
          lineHeight: 1.04,
          letterSpacing: "-0.035em",
          fontWeight: 800,
          maxWidth: 880,
          textWrap: "balance"
        }}
      >
        {HEADLINE}
      </h1>

      <div
        className="hero-grid"
        style={{
          display: "grid",
          gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)",
          gap: 36,
          marginTop: 44
        }}
      >
        <div>
          <VideoPlayer />
          <div
            style={{
              marginTop: 14,
              display: "flex",
              alignItems: "center",
              gap: 10,
              color: "var(--ink-3)",
              fontSize: 13
            }}
          >
            <Logo size={16} />
            <span>See Tadpole in action — scorecards, coaching, profitability, and Tad.</span>
          </div>
        </div>

        <div>
          <WaitlistForm />
        </div>
      </div>
    </section>
  );
}

// ===== Footer =====
function Footer() {
  return (
    <footer style={{ borderTop: "1px solid var(--line-2)", background: "#fff" }}>
      <div
        style={{
          maxWidth: 1200,
          margin: "0 auto",
          padding: "28px 24px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          flexWrap: "wrap",
          gap: 12,
          color: "var(--ink-3)",
          fontSize: 13
        }}
      >
        <Wordmark size={18} />
        <div style={{ display: "flex", gap: 18 }}>
          <span>© 2026 Tadpole</span>
          <a href="mailto:team@tadpoleapp.ai" style={{ textDecoration: "none" }}>
            team@tadpoleapp.ai
          </a>
        </div>
      </div>
    </footer>
  );
}

// ===== App =====
function App() {
  return (
    <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh" }}>
      <style>{`
        @media (max-width: 880px) {
          .hero-grid { grid-template-columns: 1fr !important; gap: 28px !important; }
        }
      `}</style>
      <Header />
      <main style={{ flex: 1 }}>
        <Hero />
      </main>
      <Footer />
    </div>
  );
}

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