import { useMemo, useState } from "react";
import { Eyebrow } from "../../lib/primitives.jsx";

export default function Confirmed({ form, queuePos }) {
  const [copied, setCopied] = useState(false);

  const ref = useMemo(() => {
    const seed = form.email || form.name || "anon";
    let h = 5;
    for (const c of seed) h = (h * 33 + c.charCodeAt(0)) >>> 0;
    return "v-" + h.toString(36).slice(0, 6);
  }, [form.email, form.name]);

  const link = typeof window !== "undefined"
    ? `${window.location.origin}/join?ref=${ref}`
    : `vibn.app/join?ref=${ref}`;

  const copyLink = () => {
    try { navigator.clipboard.writeText(link); } catch (e) { /* noop */ }
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };

  const pct = Math.max(2, Math.min(98, 100 - (queuePos - 2100) / 9));

  return (
    <div className="flex flex-col gap-7">
      <div className="text-center">
        <div className="inline-grid place-items-center w-16 h-16 rounded-full mb-4 text-ok"
             style={{
               background: "oklch(0.78 0.16 155 / 0.1)",
               border: "1px solid oklch(0.78 0.16 155 / 0.4)",
               boxShadow: "0 0 40px oklch(0.78 0.16 155 / 0.3)",
             }}>
          <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
            <circle cx="16" cy="16" r="15" stroke="currentColor" strokeWidth="1.5" opacity=".25"/>
            <path d="M10 16.5 14.5 21 22 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <Eyebrow>You're on the list</Eyebrow>
        <h1 className="mt-3.5 font-medium tracking-[-0.03em] leading-none text-[clamp(40px,6.4vw,80px)] text-balance">
          {form.name
            ? <>Welcome, <em className="not-italic text-accent" style={{ textShadow: "0 0 40px var(--c-accent-glow)" }}>{form.name}</em>.</>
            : <>You're <em className="not-italic text-accent" style={{ textShadow: "0 0 40px var(--c-accent-glow)" }}>in line</em>.</>}
        </h1>
        <p className="mt-5 text-[clamp(16px,1.6vw,19px)] text-fg-dim text-balance">
          We got your invite request — keep an eye on{" "}
          <b className="font-mono font-medium text-fg">{form.email}</b>.
        </p>
      </div>

      {/* Queue card */}
      <div className="p-7 rounded-[18px] border border-hairline"
           style={{ background: "linear-gradient(180deg, oklch(0.20 0.009 60 / 0.6), oklch(0.17 0.008 60 / 0.6))" }}>
        <div className="flex justify-between items-end gap-3.5 mb-6">
          <div>
            <div className="font-mono text-[11px] uppercase tracking-[0.1em] text-fg-faint">your spot in line</div>
            <div className="mt-2 font-mono font-medium text-accent tracking-[-0.04em] leading-none text-[clamp(48px,7vw,76px)]"
                 style={{ textShadow: "0 0 40px var(--c-accent-glow)" }}>
              #{queuePos.toLocaleString()}
            </div>
          </div>
          <div className="text-right">
            <div className="font-mono text-[26px] font-medium text-fg leading-none">
              50<small className="text-fg-mute text-[13px] font-normal ml-0.5">/wk</small>
            </div>
            <div className="font-mono text-[11px] uppercase tracking-[0.1em] text-fg-faint">letting in</div>
          </div>
        </div>

        <div className="relative h-1.5 rounded-full mb-6 mt-9" style={{ background: "oklch(0.22 0.01 60)" }}>
          <div className="absolute left-0 top-0 bottom-0 rounded-full transition-[width] duration-700"
               style={{
                 width: `${pct}%`,
                 background: "linear-gradient(90deg, oklch(0.65 0.15 35), var(--c-accent))",
                 boxShadow: "0 0 12px var(--c-accent-glow)",
               }} />
          <div className="absolute top-1/2 -translate-y-1/2 w-3.5 h-3.5 rounded-full"
               style={{
                 left: `${pct}%`,
                 transform: "translate(-50%, -50%)",
                 background: "var(--c-accent)",
                 boxShadow: "0 0 0 3px var(--c-bg), 0 0 18px var(--c-accent-glow)",
               }}>
            <span className="absolute bottom-full left-1/2 -translate-x-1/2 -translate-y-2 font-mono text-[11px] tracking-[0.04em] text-accent whitespace-nowrap">
              You
            </span>
          </div>
        </div>

        <div className="font-mono text-[12px] text-fg-mute tracking-[0.02em]">
          You should hear from us in ~<b className="text-fg font-medium">{Math.ceil((queuePos - 50) / 50)} weeks</b>. Don't want to wait?
        </div>
      </div>

      {/* Refer card */}
      <div className="p-7 rounded-[18px] border border-hairline"
           style={{ background: "linear-gradient(180deg, oklch(0.20 0.009 60 / 0.6), oklch(0.17 0.008 60 / 0.6))" }}>
        <Eyebrow>Skip the line</Eyebrow>
        <h3 className="mt-3 text-[22px] font-medium tracking-[-0.018em]">Send 3 friends — jump to the front.</h3>
        <p className="mt-1.5 text-fg-mute text-[14px]">Each friend who joins via your link bumps you up 500 spots.</p>

        <div className="mt-4 flex gap-2 items-stretch">
          <div className="flex-1 px-3.5 py-3 rounded-[10px] border border-hairline text-[13px] tracking-[0.01em] text-fg-dim flex items-center overflow-hidden whitespace-nowrap"
               style={{ background: "oklch(0.16 0.008 60)" }}>
            <span className="font-mono">
              <span className="text-fg-faint">vibn.app/join?ref=</span>
              <b className="text-accent font-medium">{ref}</b>
            </span>
          </div>
          <button type="button" onClick={copyLink} className="btn btn-ghost h-auto px-[18px]">
            {copied ? "Copied!" : "Copy link"}
          </button>
        </div>

        <div className="mt-3.5 flex flex-wrap gap-2">
          {[["x", "Share on X"], ["reddit", "Post to Reddit"], ["mail", "Email a friend"]].map(([k, label]) => (
            <a key={k} href="#"
               className="inline-flex items-center gap-2 px-3.5 py-2 rounded-full border border-hairline text-[13px] text-fg-dim transition-colors hover:text-fg hover:border-hairline-2"
               style={{ background: "oklch(0.16 0.008 60 / 0.5)" }}>
              <ShareIcon name={k} /> {label}
            </a>
          ))}
        </div>
      </div>

      {form.build && (
        <div className="p-6 px-7 rounded-2xl border border-dashed border-hairline">
          <Eyebrow>What we'll help you build first</Eyebrow>
          <div className="mt-3 italic text-fg text-[18px] tracking-[-0.005em] leading-[1.4] text-balance">
            "{form.build}"
          </div>
        </div>
      )}
    </div>
  );
}

function ShareIcon({ name }) {
  const p = { width: 14, height: 14, viewBox: "0 0 16 16", fill: "currentColor" };
  if (name === "x")      return <svg {...p}><path d="M9.2 7 13.7 2h-1.4L8.6 6.3 5.6 2H2l4.7 6.8L2 14h1.4l4.1-4.7 3.3 4.7H14L9.2 7Z"/></svg>;
  if (name === "reddit") return <svg {...p}><circle cx="8" cy="9" r="6"/></svg>;
  if (name === "mail")   return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
      <rect x="2" y="3.5" width="12" height="9" rx="1.5"/>
      <path d="m3 5 5 3.8L13 5"/>
    </svg>
  );
  return null;
}
