/* Delhi.fyi landing — small parts */

const { useState, useEffect } = React;

const SUPABASE_URL  = 'https://irziwvmnujmboteqxtze.supabase.co';
const SUPABASE_ANON = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imlyeml3dm1udWptYm90ZXF4dHplIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzcwMDIzOTcsImV4cCI6MjA5MjU3ODM5N30.hC5GRfr3fob2zCIgfR5Y37-4Nq6qllTnkL_GjQKazGY';

/* ——— Brand mark (wordmark) ——— */
function Wordmark({ size = 22 }) {
  return (
    <span className="brand" style={{ fontSize: size }} aria-label="Delhi.fyi">
      <span>Delhi</span>
      <span className="dot" style={{ width: size * 0.32, height: size * 0.32, marginLeft: 2 }}></span>
      <span style={{ marginLeft: 2 }}>fyi</span>
    </span>
  );
}

/* ——— Live Delhi clock ——— */
function DelhiClock() {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000 * 30);
    return () => clearInterval(t);
  }, []);
  const fmt = new Intl.DateTimeFormat('en-IN', {
    hour: 'numeric', minute: '2-digit', hour12: true, timeZone: 'Asia/Kolkata'
  });
  return <span>{fmt.format(now).toLowerCase()} ist</span>;
}

/* ——— Top bar ——— */
function TopBar() {
  return (
    <header className="top">
      <div className="wrap top-inner">
        <div className="brand-row">
          <Wordmark size={22} />
        </div>
        <div className="issue">
          <span><span className="live-dot" /> Coming soon</span>
          <span className="sep">·</span>
          <span>Iss. 001</span>
          <span className="sep">·</span>
          <span><DelhiClock /></span>
        </div>
      </div>
    </header>
  );
}

/* ——— Avatar stack ——— */
function Stack() {
  const people = [
    { bg: "#0A0A0A", fg: "#fff", initial: "R" },
    { bg: "#E11B22", fg: "#fff", initial: "K" },
    { bg: "#2E2E2E", fg: "#fff", initial: "A" },
    { bg: "#5C5C5C", fg: "#fff", initial: "M" },
  ];
  return (
    <span className="stack" aria-hidden>
      {people.map((p, i) => (
        <span key={i} style={{
          background: p.bg, color: p.fg,
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          fontSize: 10, fontFamily: "var(--font-sans)", fontWeight: 600,
          letterSpacing: 0.02,
        }}>{p.initial}</span>
      ))}
    </span>
  );
}

/* ——— Waitlist form (real Supabase) ——— */
function Waitlist({ startCount = 1 }) {
  const [email, setEmail]   = useState("");
  const [state, setState]   = useState("idle"); // idle | submitting | done | error
  const [error, setError]   = useState("");
  const [count, setCount]   = useState(startCount);

  useEffect(() => {
    const t = setInterval(() => {
      setCount((c) => c + (Math.random() < 0.4 ? 1 : 0));
    }, 4500);
    return () => clearInterval(t);
  }, []);

  async function submit(e) {
    e.preventDefault();
    setError("");
    const trimmed = email.trim();
    if (!trimmed) { setError("Drop an email first."); setState("error"); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
      setError("That doesn't look like an email.");
      setState("error");
      return;
    }
    setState("submitting");
    try {
      const res = await fetch(`${SUPABASE_URL}/rest/v1/waitlist`, {
        method: "POST",
        headers: {
          "apikey":        SUPABASE_ANON,
          "Authorization": `Bearer ${SUPABASE_ANON}`,
          "Content-Type":  "application/json",
          "Prefer":        "return=minimal",
        },
        body: JSON.stringify({ email: trimmed }),
      });
      if (res.ok || res.status === 201 || res.status === 409) {
        setState("done");
        setCount((c) => c + 1);
      } else {
        throw new Error(`HTTP ${res.status}`);
      }
    } catch (err) {
      setError("Something went wrong — please try again.");
      setState("error");
    }
  }

  if (state === "done") {
    return (
      <div className="signup">
        <div className="confirm" role="status" aria-live="polite">
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span className="check" aria-hidden>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M2 7.5L5.5 11L12 3.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </span>
            <h4>You're in.</h4>
          </div>
          <p>Off to the editors. We'll send word when Delhi.fyi opens — no spam, no roundups, no "weekly digests."</p>
          <p style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-60)" }}>
            {email} · saved
          </p>
        </div>
        <div className="count-row" aria-live="polite">
          <Stack />
          <span><span className="count-num">{count.toLocaleString()}</span> already in line</span>
        </div>
      </div>
    );
  }

  return (
    <form className="signup" onSubmit={submit} noValidate>
      <h3 className="signup-label">Join the waitlist.</h3>
      <p className="signup-sub">One email. We'll tell you when we open the doors.</p>
      <div className={"field-row" + (state === "error" ? " has-error" : "")}>
        <input
          type="email"
          placeholder="you@somewhere.in"
          value={email}
          onChange={(e) => { setEmail(e.target.value); if (state === "error") setState("idle"); }}
          autoComplete="email"
          aria-label="Email address"
          aria-invalid={state === "error"}
        />
        <button type="submit" disabled={state === "submitting"}>
          {state === "submitting" ? "Sending…" : <><span>Drop it</span> <span className="arr">→</span></>}
        </button>
      </div>
      {state === "error" && (
        <p className="form-error" role="alert">
          <span style={{ display: "inline-block", width: 6, height: 6, borderRadius: 999, background: "var(--red)" }} />
          {error}
        </p>
      )}
      <div className="count-row" aria-live="polite">
        <Stack />
        <span><span className="count-num">{count.toLocaleString()}</span> already in line</span>
      </div>
    </form>
  );
}

/* ——— Editors note (Disha & Aaryan) ——— */
function EditorsNote() {
  return (
    <div className="editors-note">
      <span className="salute" aria-hidden>🫡</span>
      <p className="copy">
        <strong>Disha</strong> and <strong>Aaryan</strong> are working on it. Late nights, too much coffee, a list that keeps growing. We'll send word soon.
      </p>
    </div>
  );
}

/* ——— Footer ——— */
function Footer() {
  return (
    <footer className="wrap foot">
      <h2 className="foot-mark" aria-label="Delhi.fyi">
        <span>Delhi</span>
        <span className="reddot" />
        <span>fyi</span>
      </h2>
      <div className="foot-meta">
        <div className="links">
          <a href="mailto:hello@delhi.fyi">hello@delhi.fyi</a>
          <a href="#" onClick={(e) => e.preventDefault()}>Instagram</a>
        </div>
        <div>Delhi · Gurugram · Noida</div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-40)" }}>
          © 2026 — go outside.
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Wordmark, TopBar, Waitlist, EditorsNote, Footer });
