// ============ shortenurl.id — interactive prototype ============
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

/* ---------------- Auth context ---------------- */
const AuthCtx = createContext(null);
const useAuth = () => useContext(AuthCtx);

const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [ready, setReady] = useState(false);
  const [modal, setModal] = useState(null); // null | "signin" | "signup"

  useEffect(() => {
    fetch("auth.php?action=me", { credentials: "same-origin" })
      .then(r => r.json())
      .then(d => setUser(d.email || null))
      .catch(() => {})
      .finally(() => setReady(true));
  }, []);

  const api = async (action, payload) => {
    const r = await fetch("auth.php?action=" + action, {
      method: "POST",
      credentials: "same-origin",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload || {}),
    });
    const d = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(d.error || "Something went wrong");
    return d;
  };

  const signup = (email, password) => api("signup", { email, password }).then(d => { setUser(d.email); return d; });
  const signin = (email, password) => api("signin", { email, password }).then(d => { setUser(d.email); return d; });
  const signout = () => fetch("auth.php?action=signout", { method: "POST", credentials: "same-origin" })
    .then(() => setUser(null));

  return (
    <AuthCtx.Provider value={{ user, ready, modal, setModal, signup, signin, signout }}>
      {children}
      <AuthModal/>
    </AuthCtx.Provider>
  );
};

/* ---------------- Auth modal ---------------- */
const AuthModal = () => {
  const { modal, setModal, signin, signup } = useAuth();
  const [mode, setMode] = useState("signin");
  const [email, setEmail] = useState("");
  const [pw, setPw] = useState("");
  const [showPw, setShowPw] = useState(false);
  const [msg, setMsg] = useState(null); // { type: "error"|"ok", text }
  const [busy, setBusy] = useState(false);
  const open = modal !== null;
  const firstFieldRef = useRef(null);

  // Sync mode w/ open trigger
  useEffect(() => {
    if (modal) {
      setMode(modal);
      setMsg(null);
      setBusy(false);
      setTimeout(() => firstFieldRef.current?.focus(), 280);
    }
  }, [modal]);

  // Esc to close, lock body scroll
  useEffect(() => {
    if (!open) return;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") setModal(null); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const submit = async (e) => {
    e.preventDefault();
    if (busy) return;
    setMsg(null);
    setBusy(true);
    try {
      if (mode === "signup") {
        await signup(email.trim(), pw);
        setMsg({ type: "ok", text: "Account created. Welcome." });
      } else {
        await signin(email.trim(), pw);
        setMsg({ type: "ok", text: "Welcome back." });
      }
      setTimeout(() => { setModal(null); setEmail(""); setPw(""); }, 600);
    } catch (err) {
      setMsg({ type: "error", text: err.message || "Something went wrong" });
    } finally {
      setBusy(false);
    }
  };

  return (
    <div
      className={"auth-backdrop" + (open ? " is-open" : "")}
      onMouseDown={(e) => { if (e.target === e.currentTarget) setModal(null); }}
      aria-hidden={!open}
    >
      <div className="auth-card" role="dialog" aria-modal="true" aria-labelledby="auth-title">
        <button className="auth-close" aria-label="Close" onClick={() => setModal(null)}/>

        <span className="auth-eyebrow">{mode === "signup" ? "Create account" : "Welcome back"}</span>
        <h2 id="auth-title" className="auth-title">
          {mode === "signup" ? (<>Start in <em>seconds.</em></>) : (<>Sign in to <em>your links.</em></>)}
        </h2>
        <p className="auth-sub">
          {mode === "signup"
            ? "Free forever for hobby. No credit card. Cancel any time."
            : "Pick up exactly where you left off. Analytics, slugs, QR codes — all of it."}
        </p>

        <div className={"auth-tabs " + mode} role="tablist">
          <button
            role="tab"
            aria-selected={mode === "signin"}
            className={mode === "signin" ? "is-active" : ""}
            onClick={() => { setMode("signin"); setMsg(null); }}
          >Sign in</button>
          <button
            role="tab"
            aria-selected={mode === "signup"}
            className={mode === "signup" ? "is-active" : ""}
            onClick={() => { setMode("signup"); setMsg(null); }}
          >Sign up</button>
        </div>

        <form className="auth-form" onSubmit={submit} noValidate>
          <div className="auth-field">
            <label htmlFor="auth-email">Email</label>
            <input
              ref={firstFieldRef}
              id="auth-email"
              className="auth-input"
              type="email"
              autoComplete="email"
              required
              placeholder="you@domain.id"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>

          <div className="auth-field with-toggle">
            <label htmlFor="auth-pw">Password</label>
            <input
              id="auth-pw"
              className="auth-input"
              type={showPw ? "text" : "password"}
              autoComplete={mode === "signup" ? "new-password" : "current-password"}
              required
              minLength={mode === "signup" ? 8 : undefined}
              placeholder={mode === "signup" ? "min. 8 characters" : "your password"}
              value={pw}
              onChange={(e) => setPw(e.target.value)}
            />
            <button
              type="button"
              className="auth-toggle-eye"
              aria-label={showPw ? "Hide password" : "Show password"}
              onClick={() => setShowPw(s => !s)}
            >
              {showPw ? (
                <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <path d="M2 8s2.5-4 6-4 6 4 6 4-2.5 4-6 4-6-4-6-4z"/>
                  <circle cx="8" cy="8" r="2"/>
                  <line x1="2" y1="14" x2="14" y2="2"/>
                </svg>
              ) : (
                <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <path d="M2 8s2.5-4 6-4 6 4 6 4-2.5 4-6 4-6-4-6-4z"/>
                  <circle cx="8" cy="8" r="2"/>
                </svg>
              )}
            </button>
          </div>

          {msg && <div className={"auth-msg" + (msg.type === "ok" ? " ok" : "")}>{msg.text}</div>}

          <button className="btn btn-primary auth-submit" type="submit" disabled={busy}>
            {busy
              ? (<><span className="spinner" aria-hidden="true"/> {mode === "signup" ? "Creating..." : "Signing in..."}</>)
              : (mode === "signup" ? "Create account →" : "Sign in →")}
          </button>
        </form>

        <div className="auth-divider">or continue with</div>
        <div className="auth-alt">
          <button type="button" onClick={() => setMsg({ type: "error", text: "SSO coming soon — use email for now." })}>
            <svg viewBox="0 0 16 16"><path fill="currentColor" d="M15 8.18c0-.57-.05-1.12-.14-1.64H8v3.1h3.92a3.36 3.36 0 0 1-1.45 2.2v1.82h2.35C14.18 12.4 15 10.46 15 8.18z"/><path fill="#5fa057" d="M8 15c1.96 0 3.6-.65 4.82-1.76l-2.35-1.82c-.65.44-1.49.7-2.47.7-1.9 0-3.5-1.28-4.07-3H1.49v1.88A7 7 0 0 0 8 15z"/><path fill="#e2b53f" d="M3.93 9.12A4.2 4.2 0 0 1 3.71 8c0-.39.07-.77.18-1.12V5h-2.4A7 7 0 0 0 1 8c0 1.13.27 2.2.74 3.12z"/><path fill="#e25c4c" d="M8 3.88c1.07 0 2.04.37 2.8 1.1L12.86 2.9C11.6 1.72 9.96 1 8 1A7 7 0 0 0 1.49 5.07L3.93 7c.57-1.72 2.17-3 4.07-3z"/></svg>
            Google
          </button>
          <button type="button" onClick={() => setMsg({ type: "error", text: "SSO coming soon — use email for now." })}>
            <svg viewBox="0 0 16 16"><path fill="currentColor" d="M11.2 8.5c0-1.7 1.4-2.5 1.5-2.6-.8-1.2-2.1-1.4-2.6-1.4-1.1-.1-2.1.6-2.7.6s-1.4-.6-2.3-.6c-1.2 0-2.3.7-2.9 1.8-1.2 2.1-.3 5.2.9 6.9.6.8 1.3 1.8 2.2 1.7.9 0 1.2-.6 2.3-.6s1.4.6 2.3.6c.9 0 1.6-.8 2.1-1.7.7-1 .9-1.9.9-2-.1 0-1.7-.7-1.7-2.7zM9.5 3.1C10 2.5 10.3 1.7 10.3 1c-.7 0-1.5.4-2 1-.4.5-.9 1.3-.8 2.1.8.1 1.6-.4 2-1z"/></svg>
            Apple
          </button>
        </div>

        <p className="auth-foot legal">
          By continuing you agree to our <a href="#">Terms</a> and <a href="#">Privacy</a>.
        </p>
      </div>
    </div>
  );
};

/* ---------------- User chip (logged-in nav) ---------------- */
const UserChip = () => {
  const { user, signout } = useAuth();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const onDoc = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);
  const initials = (user || "?").slice(0, 2);
  return (
    <div className={"user-chip" + (open ? " is-open" : "")} ref={ref} onClick={() => setOpen(o => !o)}>
      <span className="email">{user}</span>
      <span className="avatar">{initials}</span>
      <svg className="caret" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6">
        <path d="m4 6 4 4 4-4"/>
      </svg>
      <div className="user-menu" onClick={(e) => e.stopPropagation()}>
        <div className="menu-head">
          <div className="small">Signed in as</div>
          <div className="em">{user}</div>
        </div>
        <a href="#dashboard">Dashboard</a>
        <a href="#analytics">Analytics</a>
        <a href="#settings">Account settings</a>
        <a href="#docs">API tokens</a>
        <div className="sep"/>
        <button className="danger" onClick={() => { setOpen(false); signout(); }}>Sign out</button>
      </div>
    </div>
  );
};

/* ---------------- Icons ---------------- */
const Icon = {
  copy: (p) => (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <rect x="5" y="5" width="8" height="9" rx="1.5"/>
      <path d="M3 11V3.5A1.5 1.5 0 0 1 4.5 2H10"/>
    </svg>
  ),
  check: (p) => (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="m3 8 3.2 3L13 5"/>
    </svg>
  ),
  qr: (p) => (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <rect x="2" y="2" width="5" height="5" rx="0.5"/>
      <rect x="9" y="2" width="5" height="5" rx="0.5"/>
      <rect x="2" y="9" width="5" height="5" rx="0.5"/>
      <path d="M9 9h2v2h-2zM13 9h1M9 13h2M13 11v3"/>
    </svg>
  ),
  edit: (p) => (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M11.5 2.5 13.5 4.5 5 13H3v-2z"/>
    </svg>
  ),
  shield: (p) => (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M8 1.5 2.5 4v4c0 3.5 2.5 5.5 5.5 6.5 3-1 5.5-3 5.5-6.5V4z"/>
    </svg>
  ),
  arrowUp: (p) => (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}>
      <path d="M4 12 12 4M5.5 4H12v6.5"/>
    </svg>
  ),
  download: (p) => (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M8 2v9m0 0L4.5 7.5M8 11l3.5-3.5M2.5 13.5h11"/>
    </svg>
  ),
  twitter: (p) => (<svg viewBox="0 0 16 16" fill="currentColor" {...p}><path d="M12.1 1.5h2.2l-4.8 5.5 5.6 7.5h-4.4L7.3 9.7l-3.9 4.8H1.2L6.3 8.6 1 1.5h4.5l3.1 4.1zM11.3 13h1.2L4.7 2.7H3.4z"/></svg>),
  github: (p) => (<svg viewBox="0 0 16 16" fill="currentColor" {...p}><path d="M8 .3C3.6.3 0 3.9 0 8.4c0 3.6 2.3 6.6 5.5 7.7.4.1.5-.2.5-.4v-1.5c-2.2.5-2.7-1-2.7-1-.4-.9-.9-1.2-.9-1.2-.7-.5.1-.5.1-.5.8.1 1.2.8 1.2.8.7 1.2 1.9.9 2.4.7.1-.5.3-.9.5-1.1-1.8-.2-3.6-.9-3.6-3.9 0-.9.3-1.6.8-2.1-.1-.2-.3-1 .1-2.1 0 0 .7-.2 2.2.8.6-.2 1.3-.3 2-.3s1.4.1 2 .3c1.5-1 2.2-.8 2.2-.8.4 1.1.2 1.9.1 2.1.5.6.8 1.3.8 2.1 0 3-1.8 3.7-3.6 3.9.3.3.5.7.5 1.5v2.2c0 .2.1.5.5.4 3.2-1.1 5.5-4.1 5.5-7.7C16 3.9 12.4.3 8 .3z"/></svg>),
  linkedin: (p) => (<svg viewBox="0 0 16 16" fill="currentColor" {...p}><path d="M3.6 14.5H.6V5.4h3zM2.1 4.2C1.1 4.2.4 3.4.4 2.5S1.1.8 2.1.8s1.7.7 1.7 1.6c0 .9-.8 1.8-1.7 1.8zm13.4 10.3h-3V10c0-1.1 0-2.4-1.5-2.4s-1.7 1.2-1.7 2.4v4.5h-3V5.4h2.9v1.2h.1c.4-.8 1.4-1.5 2.8-1.5 3 0 3.5 2 3.5 4.5z"/></svg>),
  instagram: (p) => (<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}><rect x="2" y="2" width="12" height="12" rx="3.2"/><circle cx="8" cy="8" r="2.6"/><circle cx="11.6" cy="4.4" r="0.6" fill="currentColor"/></svg>),
};

/* ---------------- Brand mark ---------------- */
const Brand = ({ small }) => (
  <a href="#top" className="brand">
    <span className="brand-mark" aria-hidden="true"></span>
    <span>shortenurl<i style={{fontStyle:"italic", color:"var(--ink-soft)"}}>.id</i></span>
    {!small && <small>links / made shorter</small>}
  </a>
);

/* ---------------- NAV ---------------- */
const Nav = () => {
  const [open, setOpen] = useState(false);
  const { user, ready, setModal } = useAuth();
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  return (
    <>
      <div className="nav-rail" id="top">
        <div className="wrap nav">
          <Brand />
          <nav className="nav-links" aria-label="Primary">
            <a href="#features">Features</a>
            <a href="#analytics">Analytics</a>
            <a href="#pricing">Pricing</a>
            <a href="#docs">API</a>
            <a href="#faq">FAQ</a>
          </nav>
          <div className="nav-cta">
            {ready && user ? (
              <UserChip/>
            ) : (
              <>
                <button className="btn btn-ghost btn-sm" onClick={() => setModal("signin")}>Sign in</button>
                <button className="btn btn-primary btn-sm" onClick={() => setModal("signup")}>Start free →</button>
              </>
            )}
            <button className="nav-burger" aria-label="Menu" onClick={() => setOpen(o => !o)}>
              <span></span>
            </button>
          </div>
        </div>
      </div>
      <div className={"mobile-drawer" + (open ? " open" : "")} aria-hidden={!open}>
        <a href="#features" onClick={() => setOpen(false)}>Features</a>
        <a href="#analytics" onClick={() => setOpen(false)}>Analytics</a>
        <a href="#pricing" onClick={() => setOpen(false)}>Pricing</a>
        <a href="#docs" onClick={() => setOpen(false)}>API</a>
        <a href="#faq" onClick={() => setOpen(false)}>FAQ</a>
        <div className="drawer-cta">
          {ready && user ? (
            <>
              <div className="btn btn-ghost btn-lg" style={{justifyContent:"flex-start"}}>{user}</div>
              <button className="btn btn-primary btn-lg" onClick={() => { setOpen(false); /* signed in */ }}>Dashboard →</button>
            </>
          ) : (
            <>
              <button className="btn btn-ghost btn-lg" onClick={() => { setOpen(false); setModal("signin"); }}>Sign in</button>
              <button className="btn btn-primary btn-lg" onClick={() => { setOpen(false); setModal("signup"); }}>Start free →</button>
            </>
          )}
        </div>
      </div>
    </>
  );
};

/* ---------------- HERO ---------------- */
const Hero = () => {
  const [url, setUrl] = useState("");
  const [slug, setSlug] = useState("");
  const [results, setResults] = useState([]);
  const [copiedId, setCopiedId] = useState(null);
  const [activeOpt, setActiveOpt] = useState("auto");
  const inputRef = useRef(null);

  const makeSlug = (input) => {
    if (slug.trim()) return slug.trim().toLowerCase().replace(/[^a-z0-9-]/g, "");
    // generate a 6-char base36 slug
    return Math.random().toString(36).slice(2, 8);
  };

  const handleShorten = (e) => {
    e?.preventDefault?.();
    const trimmed = url.trim();
    if (!trimmed) {
      inputRef.current?.focus();
      return;
    }
    let safe = trimmed;
    if (!/^https?:\/\//i.test(safe)) safe = "https://" + safe;
    const s = makeSlug(safe);
    const newItem = {
      id: Date.now(),
      slug: s,
      original: safe,
    };
    setResults([newItem, ...results].slice(0, 3));
    setUrl("");
    setSlug("");
  };

  const copyResult = (item) => {
    const text = `shortenurl.id/${item.slug}`;
    navigator.clipboard?.writeText(text);
    setCopiedId(item.id);
    setTimeout(() => setCopiedId(null), 1600);
  };

  return (
    <section className="hero wrap">
      <div className="hero-eyebrow">
        <span className="eyebrow"><span className="dot"></span>Made in Indonesia · v2.4</span>
        <span className="chip"><b>NEW</b> Custom domains + UTM presets</span>
      </div>

      <div className="hero-grid">
        <div>
          <h1 className="display-xl">
            Long links,<br/>
            <span className="accent">made&nbsp;short.</span>{" "}
            <span className="italic" style={{color:"var(--ink-soft)"}}>Made smart.</span>
          </h1>
          <p className="hero-sub">
            Shorten any URL in milliseconds, track every click, generate QR codes,
            and brand your links with a custom domain. Built for marketers,
            creators, and engineers who measure what matters.
          </p>

          <form className="shortener" onSubmit={handleShorten}>
            <div className="shortener-row">
              <label className="shortener-input">
                <span className="scheme">https://</span>
                <input
                  ref={inputRef}
                  type="text"
                  value={url}
                  onChange={(e) => setUrl(e.target.value)}
                  placeholder="paste a really, really long URL here…"
                  aria-label="URL to shorten"
                />
              </label>
              <button className="btn btn-primary" type="submit">
                Shorten <Icon.arrowUp/>
              </button>
            </div>

            <div className="shortener-options">
              <div className="opt-group">
                <button
                  type="button"
                  className={"opt-pill" + (activeOpt === "auto" ? " is-active" : "")}
                  onClick={() => setActiveOpt("auto")}
                >
                  Auto slug
                </button>
                <button
                  type="button"
                  className={"opt-pill" + (activeOpt === "custom" ? " is-active" : "")}
                  onClick={() => setActiveOpt("custom")}
                >
                  <Icon.edit/> Custom
                </button>
                {activeOpt === "custom" && (
                  <input
                    className="opt-pill"
                    style={{ width: 140, fontFamily: "var(--font-mono)" }}
                    placeholder="/your-slug"
                    value={slug}
                    onChange={(e) => setSlug(e.target.value)}
                  />
                )}
                <button type="button" className="opt-pill"><Icon.qr/> QR code</button>
                <button type="button" className="opt-pill"><Icon.shield/> Password</button>
              </div>
              <span className="meta">No login required for first 5 links</span>
            </div>

            {results.map((r) => (
              <div className="result" key={r.id}>
                <div>
                  <div className="short-url">
                    <span className="host">shortenurl.id/</span>
                    <span className="slug">{r.slug}</span>
                  </div>
                  <span className="short-url original">{r.original}</span>
                </div>
                <div className="result-actions">
                  <button
                    className={"icon-btn" + (copiedId === r.id ? " copied" : "")}
                    onClick={() => copyResult(r)}
                    aria-label="Copy short link"
                  >
                    {copiedId === r.id ? <Icon.check/> : <Icon.copy/>}
                  </button>
                  <button className="icon-btn" aria-label="QR code"><Icon.qr/></button>
                </div>
                <a
                  className="btn btn-primary"
                  href={r.original}
                  target="_blank"
                  rel="noreferrer"
                  style={{height:40, padding:"0 16px", fontSize:13}}
                >
                  Open ↗
                </a>
              </div>
            ))}
          </form>
        </div>

        <LiveTape/>
      </div>

      <StatsStrip/>
    </section>
  );
};

/* ---------------- Live tape (right column) ---------------- */
const seedRows = [
  { flag: "ID", path: "shortenurl.id/promo-25", page: "Tokopedia · Ramadan Sale", ago: "just now" },
  { flag: "SG", path: "shortenurl.id/launch", page: "Notion · Product update", ago: "2s" },
  { flag: "US", path: "shortenurl.id/dl-mac", page: "Figma · macOS installer", ago: "3s" },
  { flag: "JP", path: "shortenurl.id/ig-bio", page: "Instagram · bio link", ago: "5s" },
  { flag: "MY", path: "shortenurl.id/podcast", page: "Spotify · ep. 42", ago: "8s" },
  { flag: "AU", path: "shortenurl.id/menu", page: "QR card · Kopi Tuku menu", ago: "11s" },
  { flag: "DE", path: "shortenurl.id/whitepaper", page: "Linear · annual report", ago: "14s" },
  { flag: "GB", path: "shortenurl.id/blog-ai", page: "Substack · The Pragmatic AI", ago: "17s" },
];

const LiveTape = () => {
  const [rows, setRows] = useState(seedRows);
  const sources = useRef(seedRows).current;

  useEffect(() => {
    const id = setInterval(() => {
      setRows((curr) => {
        const next = [
          { ...sources[Math.floor(Math.random() * sources.length)], ago: "just now" },
          ...curr.map((r, i) => ({ ...r, ago: bump(r.ago, i) })),
        ].slice(0, 7);
        return next;
      });
    }, 2200);
    return () => clearInterval(id);
  }, []);

  function bump(ago, i) {
    if (ago === "just now") return "2s";
    const n = parseInt(ago, 10);
    if (Number.isFinite(n)) return (n + 3) + "s";
    return ago;
  }

  return (
    <div className="tape">
      <div className="tape-head">
        <span className="tag">Realtime · global clicks</span>
        <span className="live"><span className="pulse"></span>Live</span>
      </div>
      {rows.map((r, i) => (
        <div className="tape-row" key={r.path + i + r.ago}>
          <span className="flag">{r.flag}</span>
          <div className="path">
            <b>{r.path}</b>
            <div style={{fontFamily:"var(--font-sans)", color:"var(--ink-muted)", fontSize:12, marginTop:2}}>
              {r.page}
            </div>
          </div>
          <span className="time">{r.ago}</span>
        </div>
      ))}
    </div>
  );
};

/* ---------------- STATS ---------------- */
const StatsStrip = () => (
  <div className="stats">
    <div className="stat">
      <div className="num">182<em>M</em></div>
      <div className="label">Links shortened</div>
    </div>
    <div className="stat">
      <div className="num">6.4<em>B</em></div>
      <div className="label">Clicks tracked</div>
    </div>
    <div className="stat">
      <div className="num">99.99<em>%</em></div>
      <div className="label">Uptime · 2025</div>
    </div>
    <div className="stat">
      <div className="num">42<em>ms</em></div>
      <div className="label">Avg. redirect</div>
    </div>
  </div>
);

/* ---------------- FEATURES ---------------- */
const Features = () => (
  <section className="section wrap" id="features">
    <div className="feature-head">
      <div>
        <span className="eyebrow"><span className="dot"></span>Capabilities</span>
        <h2 className="h2" style={{marginTop:18}}>
          One tiny link.<br/>
          <span className="italic" style={{color:"var(--ink-soft)"}}>Everything you need.</span>
        </h2>
      </div>
      <p className="lead">
        Behind every short link sits a full toolkit: live analytics, branded
        domains, targeting rules, QR codes, password protection, and a
        no-fuss API. No surprises, no upsells for the basics.
      </p>
    </div>

    <div className="feature-grid">
      <div className="feature span-3">
        <div>
          <span className="ftag">01 · Analytics</span>
          <div className="ftitle" style={{marginTop:14}}>Click data that<br/>actually tells a story.</div>
        </div>
        <div className="illus analytics">
          {[28, 44, 36, 62, 48, 88, 70, 92, 64, 52, 76, 58].map((h, i) => (
            <div key={i} className={"bar" + (h > 75 ? " high" : "")} style={{height: h + "%"}}/>
          ))}
        </div>
      </div>

      <div className="feature span-3 dark">
        <div>
          <span className="ftag">02 · QR Codes</span>
          <div className="ftitle" style={{marginTop:14, color:"var(--paper)"}}>Print it. Scan it.<br/>Track it the same.</div>
          <p className="fbody" style={{marginTop:16}}>Every short link comes with a dynamic QR you can restyle, re-route, and re-print without changing the code.</p>
        </div>
        <div style={{display:"flex", justifyContent:"flex-end"}}>
          <div className="illus qr">
            {Array.from({length: 49}).map((_, i) => {
              const r = (i * 7919) % 100;
              const cls = r < 18 ? "off" : (r > 92 ? "signal" : "");
              return <span key={i} className={cls}/>;
            })}
          </div>
        </div>
      </div>

      <div className="feature span-2">
        <div>
          <span className="ftag">03 · Branded slugs</span>
          <div className="ftitle" style={{marginTop:14}}>Your domain.<br/>Your slug.</div>
        </div>
        <div className="illus slug">
          <div className="row"><span className="sl">brand.co/<b>summer-sale</b></span><span style={{color:"var(--ink-muted)"}}>✓</span></div>
          <div className="row signal"><span className="sl">go.brand.co/<b>launch</b></span><span>✓</span></div>
          <div className="row"><span className="sl">l.brand.co/<b>bio</b></span><span style={{color:"var(--ink-muted)"}}>✓</span></div>
        </div>
      </div>

      <div className="feature span-2 signal">
        <div>
          <span className="ftag">04 · Smart routing</span>
          <div className="ftitle" style={{marginTop:14}}>One link → many destinations.</div>
          <p className="fbody" style={{marginTop:16}}>Route by country, device, language, or time-of-day. iOS goes to App Store, Android to Play Store, the rest to your landing page.</p>
        </div>
        <div style={{display:"flex", gap:8, fontFamily:"var(--font-mono)", fontSize:12, flexWrap:"wrap"}}>
          <span style={{padding:"4px 10px", background:"rgba(14,20,16,0.08)", borderRadius:999}}>iOS → App Store</span>
          <span style={{padding:"4px 10px", background:"rgba(14,20,16,0.08)", borderRadius:999}}>Android → Play</span>
          <span style={{padding:"4px 10px", background:"rgba(14,20,16,0.08)", borderRadius:999}}>ID → /id</span>
        </div>
      </div>

      <div className="feature span-2">
        <div>
          <span className="ftag">05 · Built-in security</span>
          <div className="ftitle" style={{marginTop:14}}>Spam filters &amp; password gates.</div>
          <p className="fbody" style={{marginTop:16}}>We scan every destination against six threat databases before the redirect resolves. Add a password for anything sensitive.</p>
        </div>
        <div style={{display:"grid", gap:8, fontFamily:"var(--font-mono)", fontSize:12}}>
          <div style={{display:"flex", justifyContent:"space-between", padding:"10px 12px", background:"var(--canvas)", borderRadius:8}}>
            <span>google-safe-browsing</span><span style={{color:"#1f9c4d"}}>● ok</span>
          </div>
          <div style={{display:"flex", justifyContent:"space-between", padding:"10px 12px", background:"var(--canvas)", borderRadius:8}}>
            <span>phishtank</span><span style={{color:"#1f9c4d"}}>● ok</span>
          </div>
          <div style={{display:"flex", justifyContent:"space-between", padding:"10px 12px", background:"var(--canvas)", borderRadius:8}}>
            <span>urlhaus</span><span style={{color:"#1f9c4d"}}>● ok</span>
          </div>
        </div>
      </div>

      <div className="feature span-4 dark">
        <div>
          <span className="ftag">06 · Developer API</span>
          <div className="ftitle" style={{marginTop:14, color:"var(--paper)"}}>A two-line API your team will actually like.</div>
        </div>
        <div className="illus api">
{`<span class="c"># shorten a link</span>
curl -X POST https://api.shortenurl.id/v1/links \\
  -H <span class="s">"Authorization: Bearer $TOKEN"</span> \\
  -d '{<span class="k">"url"</span>: <span class="s">"https://example.com/very/long/path?utm=email"</span>}'

<span class="c"># → 200 OK</span>
{ <span class="k">"slug"</span>: <span class="s">"k9aZx2"</span>, <span class="k">"short"</span>: <span class="s">"https://shortenurl.id/k9aZx2"</span> }`.split("\n").map((line, i) => (
  <div key={i} dangerouslySetInnerHTML={{__html: line}}/>
))}
        </div>
      </div>
    </div>

    <div className="steps">
      <div className="step">
        <span className="n">— 01</span>
        <h3>Paste your long URL</h3>
        <p>Drop any link, any length. We don't care how ugly the query string is — paste and forget.</p>
      </div>
      <div className="step">
        <span className="n">— 02</span>
        <h3>Customize &amp; brand it</h3>
        <p>Choose a slug, attach a QR, gate it with a password, or route by region. All optional, all instant.</p>
      </div>
      <div className="step">
        <span className="n">— 03</span>
        <h3>Share &amp; measure</h3>
        <p>Drop it in DMs, ads, podcasts, or print. Open the dashboard and watch clicks land on the map in realtime.</p>
      </div>
    </div>
  </section>
);

/* ---------------- ANALYTICS PREVIEW ---------------- */
const Analytics = () => {
  // Generate a smooth-ish line chart
  const points = useMemo(() => {
    const days = 30;
    const arr = [];
    let v = 40;
    for (let i = 0; i < days; i++) {
      v += (Math.sin(i * 0.7) * 12) + (Math.random() * 14 - 5);
      v = Math.max(20, Math.min(95, v));
      arr.push(v);
    }
    return arr;
  }, []);

  const pathD = useMemo(() => {
    const w = 1000, h = 200, n = points.length;
    const stepX = w / (n - 1);
    let d = "";
    points.forEach((p, i) => {
      const x = i * stepX;
      const y = h - (p / 100) * h;
      d += (i === 0 ? "M" : "L") + x.toFixed(1) + "," + y.toFixed(1) + " ";
    });
    return d;
  }, [points]);

  const areaD = useMemo(() => {
    const w = 1000, h = 200, n = points.length;
    const stepX = w / (n - 1);
    let d = "M0," + h + " ";
    points.forEach((p, i) => {
      const x = i * stepX;
      const y = h - (p / 100) * h;
      d += "L" + x.toFixed(1) + "," + y.toFixed(1) + " ";
    });
    d += "L" + w + "," + h + " Z";
    return d;
  }, [points]);

  const top = [
    { cc:"ID", url:"/ramadan-25", page:"Tokopedia · Promo Ramadan", clicks: "14,392", pct: 84 },
    { cc:"ID", url:"/menu-tuku", page:"Kopi Tuku · QR menu",       clicks: "8,201",  pct: 62 },
    { cc:"SG", url:"/launch-pro", page:"Linear · Pro launch",      clicks: "6,558",  pct: 48 },
    { cc:"US", url:"/dl-mac",    page:"Figma · macOS installer",  clicks: "4,109",  pct: 32 },
    { cc:"JP", url:"/ig-bio",    page:"Instagram bio link",       clicks: "2,884",  pct: 22 },
  ];

  return (
    <section className="wrap" id="analytics">
      <div className="analytics-section">
        <span className="eyebrow"><span className="dot"></span>Live dashboard</span>
        <h2 className="h2" style={{marginTop:18, maxWidth:"18ch"}}>
          See where every click<br/>
          <span className="italic" style={{color:"var(--signal)"}}>actually</span> comes from.
        </h2>
        <p className="lead" style={{marginTop:16, color:"rgba(255,255,255,0.65)"}}>
          Country, city, device, browser, referrer, UTM, and time-of-day —
          all without cookies, all GDPR-friendly, all visible in a single view.
        </p>

        <div className="dash">
          <div className="dash-card">
            <div className="label">Clicks · 30 days</div>
            <div className="big">36,1<em>44</em></div>
            <div className="delta">↑ 28.4% vs prev. period</div>
          </div>
          <div className="dash-card">
            <div className="label">Unique visitors</div>
            <div className="big">21,9<em>03</em></div>
            <div className="delta">↑ 19.1% vs prev. period</div>
          </div>

          <div className="dash-chart">
            <svg viewBox="0 0 1000 200" preserveAspectRatio="none">
              <defs>
                <linearGradient id="g1" x1="0" x2="0" y1="0" y2="1">
                  <stop offset="0%" stopColor="#d4ff3a" stopOpacity="0.35"/>
                  <stop offset="100%" stopColor="#d4ff3a" stopOpacity="0"/>
                </linearGradient>
              </defs>
              {/* gridlines */}
              {[0, 50, 100, 150].map((y) => (
                <line key={y} x1="0" x2="1000" y1={y} y2={y} stroke="rgba(255,255,255,0.06)" strokeWidth="1"/>
              ))}
              <path d={areaD} fill="url(#g1)"/>
              <path d={pathD} fill="none" stroke="#d4ff3a" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
              {points.map((p, i) => {
                if (i % 4 !== 0) return null;
                const x = (i / (points.length - 1)) * 1000;
                const y = 200 - (p / 100) * 200;
                return <circle key={i} cx={x} cy={y} r="2.2" fill="#0e1410" stroke="#d4ff3a" strokeWidth="1.5"/>;
              })}
            </svg>
          </div>

          <div className="dash-list">
            {top.map((t, i) => (
              <div className="row" key={i}>
                <span className="country">{t.cc}</span>
                <div className="url"><b>shortenurl.id{t.url}</b><small>{t.page}</small></div>
                <span className="meter"><span style={{width: t.pct + "%"}}/></span>
                <span className="clicks">{t.clicks}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

/* ---------------- USE CASES ---------------- */
const Cases = () => (
  <section className="section wrap">
    <div className="feature-head">
      <div>
        <span className="eyebrow"><span className="dot"></span>Built for</span>
        <h2 className="h2" style={{marginTop:18}}>
          Wherever a link lives,<br/>
          <span className="italic" style={{color:"var(--ink-soft)"}}>we make it work harder.</span>
        </h2>
      </div>
    </div>
    <div className="cases">
      {[
        { g:"M", t:"Marketers", p:"Campaign UTMs, deep links, A/B variants, and exportable reports your CMO will actually read." },
        { g:"C", t:"Creators",  p:"One bio-link page, infinite destinations. Track which post drives which click." },
        { g:"E", t:"Engineers", p:"REST + GraphQL APIs, webhooks for every click, and SDKs for Node, Go, Python and PHP." },
        { g:"R", t:"Retail",    p:"QR codes on packaging, posters, receipts — re-route stale links without re-printing a thing." },
      ].map((c) => (
        <div className="case" key={c.t}>
          <div className="glyph">{c.g}</div>
          <div>
            <div className="case-title">{c.t}</div>
            <p>{c.p}</p>
          </div>
        </div>
      ))}
    </div>
  </section>
);

/* ---------------- PRICING ---------------- */
const Pricing = () => {
  const [annual, setAnnual] = useState(true);
  const { setModal } = useAuth();
  const plans = [
    {
      name: "Hobby",
      monthly: 0,
      annual: 0,
      sub: "Free forever. No credit card.",
      cta: "Start free",
      ctaClass: "btn-ghost",
      features: [
        ["50", "short links / month"],
        ["", "Basic click analytics (7 days)"],
        ["", "Generated QR codes"],
        ["", "Single shortenurl.id domain"],
      ],
    },
    {
      name: "Pro",
      monthly: 12,
      annual: 9,
      sub: "For creators and small teams.",
      cta: "Start 14-day trial",
      ctaClass: "btn-primary",
      featured: true,
      features: [
        ["Unlimited", "short links"],
        ["1 yr", "of click analytics history"],
        ["3", "custom branded domains"],
        ["", "Smart routing by geo / device"],
        ["", "Password &amp; expiry controls"],
        ["", "Bulk import via CSV (10k rows)"],
      ],
    },
    {
      name: "Business",
      monthly: 39,
      annual: 29,
      sub: "Teams, agencies, and APIs at scale.",
      cta: "Talk to sales",
      ctaClass: "btn-ghost",
      features: [
        ["Everything", "in Pro, plus"],
        ["Unlimited", "custom domains &amp; workspaces"],
        ["SSO", "+ SAML and audit logs"],
        ["", "5M API calls / month"],
        ["", "99.99% uptime SLA"],
        ["", "Priority support · 4hr response"],
      ],
    },
  ];

  return (
    <section className="section wrap" id="pricing">
      <div className="feature-head" style={{alignItems:"start"}}>
        <div>
          <span className="eyebrow"><span className="dot"></span>Pricing</span>
          <h2 className="h2" style={{marginTop:18}}>
            Honest pricing.<br/>
            <span className="italic" style={{color:"var(--ink-soft)"}}>No per-click nonsense.</span>
          </h2>
          <div className="pricing-toggle" role="tablist" aria-label="Billing cycle">
            <button className={!annual ? "is-active" : ""} onClick={() => setAnnual(false)}>Monthly</button>
            <button className={annual ? "is-active" : ""} onClick={() => setAnnual(true)}>
              Annual <span className="save">SAVE 25%</span>
            </button>
          </div>
        </div>
        <p className="lead">
          Pay for what you use. Every plan includes unlimited clicks,
          unlimited team-mates on Pro+, and the same analytics engine.
          No "starter" gotchas.
        </p>
      </div>

      <div className="plans">
        {plans.map((p) => {
          const price = annual ? p.annual : p.monthly;
          return (
            <div className={"plan" + (p.featured ? " feature-plan" : "")} key={p.name}>
              {p.featured && <span className="ribbon">Most popular</span>}
              <div>
                <h3>{p.name}</h3>
                <p style={{margin:"6px 0 0", fontSize:14, color: p.featured ? "rgba(255,255,255,0.7)" : "var(--ink-soft)"}}>{p.sub}</p>
              </div>
              <div className="price">
                {price === 0 ? (
                  <>
                    <span>Free</span>
                  </>
                ) : (
                  <>
                    <span className="currency">$</span>
                    <span>{price}</span>
                    <span className="per">/ mo</span>
                  </>
                )}
              </div>
              {price > 0 && (
                <div className="price-sub">
                  Billed {annual ? `annually · $${price * 12}/yr` : "month-to-month"}
                </div>
              )}
              {p.cta === "Talk to sales"
                ? <a className={"btn btn-lg " + p.ctaClass} href="mailto:hello@shortenurl.id">{p.cta}</a>
                : <button className={"btn btn-lg " + p.ctaClass} onClick={() => setModal("signup")}>{p.cta}</button>}
              <ul>
                {p.features.map((f, i) => (
                  <li key={i}>
                    <span dangerouslySetInnerHTML={{__html: f[0] ? `<b>${f[0]}</b> ${f[1]}` : f[1]}}/>
                  </li>
                ))}
              </ul>
            </div>
          );
        })}
      </div>
    </section>
  );
};

/* ---------------- FAQ ---------------- */
const Faq = () => {
  const [open, setOpen] = useState(0);
  const items = [
    {
      q: "Do my short links ever expire or break?",
      a: "Never. Links you create on shortenurl.id are permanent — even on the free tier. If a destination moves, you can re-point the link without changing the short URL, so anything you've already printed or posted keeps working."
    },
    {
      q: "Can I use my own domain?",
      a: "Yes. On Pro and Business you can connect any domain you own — go.yourbrand.com, l.yourbrand.id, even a single-letter root. We handle the SSL certificate and DNS validation, usually in under five minutes."
    },
    {
      q: "How accurate are the click analytics?",
      a: "We log every successful redirect server-side, so there's no ad-blocker drift. We exclude obvious bots and double-clicks within a 30-second window. You'll get country, city, device, browser, OS, referrer, and UTM parameters on every click."
    },
    {
      q: "Is shortenurl.id GDPR / UU PDP compliant?",
      a: "Yes. We don't use cookies for analytics, we anonymise IP addresses at edge, and we offer EU-only data residency on Business plans. We're registered under Indonesia's UU PDP and publish a public DPA."
    },
    {
      q: "What happens if I cancel?",
      a: "Your links keep redirecting forever — we never break a working link. You'll lose access to new analytics and the dashboard, but everything you created stays alive on a read-only basis."
    },
    {
      q: "Do you have a free tier for nonprofits or students?",
      a: "Yes. Registered nonprofits get Business for free; students with a .edu / .ac.id email get Pro for free. Send proof of status to hello@shortenurl.id and we'll flip the switch the same day."
    },
  ];

  return (
    <section className="section wrap" id="faq">
      <div className="faq-grid">
        <div>
          <span className="eyebrow"><span className="dot"></span>FAQ</span>
          <h2 className="h2" style={{marginTop:18}}>
            Things people<br/>
            <span className="italic" style={{color:"var(--ink-soft)"}}>actually ask.</span>
          </h2>
          <p className="lead" style={{marginTop:20}}>
            Can't find what you need? Email <a href="mailto:hello@shortenurl.id" style={{color:"var(--ink)", textDecoration:"underline"}}>hello@shortenurl.id</a> and a real human will reply within a working day.
          </p>
        </div>
        <div className="faq-list">
          {items.map((it, i) => (
            <div key={i} className={"faq-item" + (open === i ? " is-open" : "")}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                {it.q}
                <span className="toggle"></span>
              </button>
              <div className="faq-a">{it.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ---------------- CTA BAND ---------------- */
const CtaBand = () => {
  const { user, setModal } = useAuth();
  return (
    <section className="wrap" id="start">
      <div className="cta-band">
        <div>
          <span className="eyebrow" style={{color:"rgba(14,20,16,0.55)"}}><span className="dot" style={{background:"var(--ink)", boxShadow:"none"}}></span>Get started</span>
          <h2 className="h2" style={{marginTop:14}}>
            Shorten your first link<br/>
            <span className="italic">in eleven seconds.</span>
          </h2>
          <p>No credit card, no email gate, no 14-step onboarding. Paste a URL, get a link, share it.</p>
        </div>
        <div className="cta-actions">
          {user
            ? <a className="btn btn-primary btn-lg" href="#top">Go to dashboard →</a>
            : <button className="btn btn-primary btn-lg" onClick={() => setModal("signup")}>Create account →</button>}
          <a className="btn btn-ghost btn-lg" href="#docs">Read the docs</a>
        </div>
      </div>
    </section>
  );
};

/* ---------------- FOOTER ---------------- */
const Footer = () => {
  const { user, setModal } = useAuth();
  return (
  <footer className="footer">
    <div className="wrap">
      <div className="footer-grid">
        <div className="footer-brand">
          <Brand small/>
          <p>The Indonesian URL shortener for marketers, creators, and engineers who measure what matters. Made in Jakarta, served from 200+ edge cities.</p>
          <div style={{display:"flex", gap:8}}>
            {user
              ? <a className="btn btn-primary btn-sm" href="#top">Dashboard</a>
              : <button className="btn btn-primary btn-sm" onClick={() => setModal("signup")}>Start free</button>}
            <a className="btn btn-ghost btn-sm" style={{borderColor:"rgba(255,255,255,0.18)", color:"var(--paper)"}} href="#docs">Read docs</a>
          </div>
        </div>
        <div className="col-products">
          <h4>Product</h4>
          <ul>
            <li><a href="#">URL shortener</a></li>
            <li><a href="#">QR generator</a></li>
            <li><a href="#">Link-in-bio</a></li>
            <li><a href="#">Branded domains</a></li>
            <li><a href="#">Smart routing</a></li>
            <li><a href="#">Click analytics</a></li>
          </ul>
        </div>
        <div className="col-resources">
          <h4>Resources</h4>
          <ul>
            <li><a href="#">Developer API</a></li>
            <li><a href="#">Help center</a></li>
            <li><a href="#">Changelog</a></li>
            <li><a href="#">Status</a></li>
            <li><a href="#">Blog</a></li>
            <li><a href="#">Press kit</a></li>
          </ul>
        </div>
        <div className="col-company">
          <h4>Company</h4>
          <ul>
            <li><a href="#">About</a></li>
            <li><a href="#">Customers</a></li>
            <li><a href="#">Careers <span style={{color:"var(--signal)", fontSize:11, marginLeft:6}}>WE'RE HIRING</span></a></li>
            <li><a href="#">Partners</a></li>
            <li><a href="#">Contact</a></li>
          </ul>
        </div>
        <div className="col-legal">
          <h4>Legal</h4>
          <ul>
            <li><a href="#">Terms of service</a></li>
            <li><a href="#">Privacy policy</a></li>
            <li><a href="#">DPA</a></li>
            <li><a href="#">Acceptable use</a></li>
            <li><a href="#">UU PDP notice</a></li>
            <li><a href="#">Report abuse</a></li>
          </ul>
        </div>
      </div>

      <div className="footer-sub">
        <span>© 2026 Shortenurl.id · PT Tautan Pendek Nusantara · Jakarta, Indonesia</span>
        <div className="socials">
          <a href="#" aria-label="Twitter"><Icon.twitter style={{width:14, height:14}}/></a>
          <a href="#" aria-label="GitHub"><Icon.github style={{width:14, height:14}}/></a>
          <a href="#" aria-label="LinkedIn"><Icon.linkedin style={{width:14, height:14}}/></a>
          <a href="#" aria-label="Instagram"><Icon.instagram style={{width:14, height:14}}/></a>
        </div>
      </div>

      <div className="giant-mark">shortenurl<span style={{fontStyle:"italic"}}>.id</span></div>
    </div>
  </footer>
  );
};

/* ---------------- APP ---------------- */
const App = () => (
  <AuthProvider>
    <Nav/>
    <Hero/>
    <Features/>
    <Analytics/>
    <Cases/>
    <Pricing/>
    <Faq/>
    <CtaBand/>
    <Footer/>
  </AuthProvider>
);

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