/**
 * The first thing a stranger sees.
 *
 * This route is what gets pasted into a message to someone at Prime Intellect,
 * and until they type the code it is the entire product as far as they are
 * concerned. It was a bare label, an input and a button — a form, with no
 * indication of what it opened. So the gate is now the hero: it says whose
 * page this is, what is behind the code, and how long the access lasts, and
 * the input is the largest thing on the screen.
 *
 * The right-hand panel is ornament and is marked as such. It is a locked
 * poster, not a fake video: inventing a plausible-looking thumbnail with a
 * made-up title would be a promise about content that may not exist.
 */
import { useState, type FormEvent } from 'react';
import { useMutation } from '@tanstack/react-query';
import { ArrowRight, Lock, PlayCircle } from 'lucide-react';
import { toast } from 'sonner';
import { ApiError } from '@/lib/api';
import { Button, Input } from '@/components/ui';

/** Uneven on purpose — three identical bars read as a loading state. */
const BAR_WIDTHS = [{ width: '78%' }, { width: '58%' }, { width: '68%' }];

export function LearnAccessHero({ onUnlocked }: { onUnlocked: (token: string) => void }) {
  const [code, setCode] = useState('');

  const unlock = useMutation({
    mutationFn: async (value: string) => {
      const response = await fetch('/api/learn/access', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ code: value }),
      });
      const body = (await response.json().catch(() => ({}))) as {
        token?: string;
        error?: string;
        code?: string;
      };
      if (!response.ok || !body.token) {
        throw new ApiError(body.error ?? 'That code is not valid.', response.status, body.code);
      }
      return body.token;
    },
    onSuccess: (minted) => {
      onUnlocked(minted);
      toast.success('Unlocked. Here are the product walkthroughs.');
    },
    onError: (error: unknown) => {
      toast.error(error instanceof Error ? error.message : 'That code is not valid.');
    },
  });

  function submit(event: FormEvent) {
    event.preventDefault();
    const trimmed = code.trim();
    if (!trimmed) return;
    unlock.mutate(trimmed);
  }

  return (
    <section className="relative min-w-0 overflow-hidden rounded-3xl border border-border bg-surface">
      <div
        className="absolute inset-0 bg-[radial-gradient(circle_at_82%_-10%,hsl(var(--accent-subtle)),transparent_58%),radial-gradient(circle_at_-5%_110%,hsl(var(--surface-2)),transparent_55%)]"
        aria-hidden
      />

      <div className="relative grid min-w-0 gap-10 p-6 sm:p-10 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)] lg:items-center lg:gap-12 lg:p-14">
        <div className="flex min-w-0 flex-col gap-5">
          <span className="inline-flex w-fit min-w-0 items-center gap-2 rounded-full border border-border bg-surface px-3 py-1 text-xs font-medium text-muted">
            <PlayCircle className="size-3.5 shrink-0 text-accent-fg" aria-hidden />
            <span className="min-w-0">Shared preview · Prime Intellect Growth</span>
          </span>

          <h1 className="min-w-0 text-3xl font-semibold leading-[1.1] tracking-tight sm:text-4xl lg:text-[2.75rem]">
            See how PIG runs both sides of the book.
          </h1>

          <p className="min-w-0 max-w-xl text-base leading-7 text-muted">
            Short product walkthroughs: what the platform does with contracted capacity, how it
            joins what we bought to what we sold, and what the numbers on the margin report
            actually mean. Enter the code you were given to watch them.
          </p>

          <form onSubmit={submit} className="flex min-w-0 flex-col gap-2 pt-1 sm:flex-row">
            <div className="min-w-0 flex-1">
              <label htmlFor="learn-code" className="sr-only">
                Access code
              </label>
              <Input
                id="learn-code"
                value={code}
                onChange={(event) => setCode(event.target.value)}
                autoComplete="off"
                autoCapitalize="none"
                spellCheck={false}
                placeholder="Enter your access code"
                className="h-12 w-full min-w-0 bg-surface text-base"
              />
            </div>
            <Button
              type="submit"
              variant="primary"
              size="lg"
              className="shrink-0"
              disabled={unlock.isPending || !code.trim()}
            >
              {unlock.isPending ? 'Checking…' : 'Unlock'}
              {unlock.isPending ? null : <ArrowRight className="size-4" aria-hidden />}
            </Button>
          </form>

          <p className="min-w-0 text-sm text-muted">
            Whoever shared this page has the code. Access lasts twelve hours and covers the
            platform walkthroughs only.{' '}
            <a href="/" className="font-medium text-accent-fg underline underline-offset-4">
              Have a PIG account? Sign in
            </a>
            .
          </p>
        </div>

        {/*
          Decorative, and hidden from assistive technology: it carries no
          information the copy has not already given. Redacted bars rather than
          invented titles — a plausible-looking fake thumbnail is a promise
          about content that may not exist.
        */}
        <div className="hidden min-w-0 lg:block" aria-hidden>
          <div className="relative flex min-w-0 flex-col gap-3 rounded-2xl border border-border bg-surface/70 p-4 shadow-sm backdrop-blur-sm">
            {[0, 1, 2].map((row) => (
              <div key={row} className="flex min-w-0 items-center gap-3">
                <div className="relative aspect-video w-24 shrink-0 overflow-hidden rounded-lg border border-border bg-gradient-to-br from-accent-subtle via-surface-2 to-surface">
                  <span className="absolute inset-0 flex items-center justify-center text-muted">
                    <Lock className="size-4" strokeWidth={1.75} />
                  </span>
                </div>
                <div className="flex min-w-0 flex-1 flex-col gap-2">
                  <span className="block h-2.5 rounded-full bg-fg/[0.09]" style={BAR_WIDTHS[row]} />
                  <span className="block h-2 w-full rounded-full bg-fg/[0.05]" />
                  <span className="block h-2 w-2/3 rounded-full bg-fg/[0.05]" />
                </div>
              </div>
            ))}
            <p className="border-t border-border pt-3 text-center text-sm font-medium text-muted">
              Product walkthroughs, waiting on a code.
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}
