import { useState } from "react";
import { Button, Divider, Stack, Text, TextInput } from "@mantine/core";
import { IconLink, IconRotateClockwise, IconShieldLock } from "@tabler/icons-react";
import { AuthCard, AuthHeader } from "./AuthShell";

// extractToken pulls the invite token out of whatever the user pastes: a full
// link (.../join?token=XXX), a bare "token=XXX", or just the token itself.
function extractToken(input: string): string {
  const s = input.trim();
  if (!s) return "";
  const m = s.match(/[?&]token=([^&\s]+)/);
  if (m) return decodeURIComponent(m[1]);
  if (s.startsWith("token=")) return s.slice("token=".length);
  return s;
}

// Welcome is the entry screen on a device with no local identity. It offers the
// two ways in: open an invite link (new account) or recover an existing account
// from its 12-word seed.
export function Welcome({
  onJoinToken,
  onRecover,
}: {
  onJoinToken: (token: string) => void;
  onRecover: () => void;
}) {
  const [link, setLink] = useState("");
  const token = extractToken(link);

  return (
    <AuthCard width={420}>
      <AuthHeader
        icon={<IconShieldLock size={30} />}
        title="unibus"
        subtitle="Mensajería cifrada de extremo a extremo. Tu identidad vive en tu dispositivo."
      />

      <Stack gap="xs">
        <Text size="sm" fw={600}>
          Tengo un enlace de invitación
        </Text>
        <TextInput
          placeholder="Pega aquí tu enlace /join?token=…"
          leftSection={<IconLink size={16} />}
          value={link}
          onChange={(e) => setLink(e.currentTarget.value)}
          onKeyDown={(e) => e.key === "Enter" && token && onJoinToken(token)}
        />
        <Button disabled={!token} onClick={() => onJoinToken(token)}>
          Crear mi cuenta
        </Button>
      </Stack>

      <Divider label="o" labelPosition="center" color="dark.4" />

      <Stack gap="xs">
        <Text size="sm" fw={600}>
          Ya tengo una cuenta
        </Text>
        <Button
          variant="default"
          leftSection={<IconRotateClockwise size={16} />}
          onClick={onRecover}
        >
          Recuperar con mi seed (12 palabras)
        </Button>
      </Stack>
    </AuthCard>
  );
}
