"use client";

import Link from "next/link";
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
import { ArrowDown, ArrowRight } from "lucide-react";
import type { HeroData, VariantData } from "@/lib/comando";
import {
  initialOverrideAssignment,
  resolveAndPersistAssignment,
  type ExperimentAssignment,
} from "@/lib/experiments";

type ExperimentContextValue = {
  assignment?: ExperimentAssignment;
  activeVariant?: VariantData;
  ready: boolean;
};

const ExperimentContext = createContext<ExperimentContextValue>({ ready: false });

function anonymousId() {
  if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
  const bytes = crypto.getRandomValues(new Uint8Array(16));
  return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
}

export function ExperimentProvider({
  route,
  variants,
  requestedVariant,
  children,
}: {
  route: string;
  variants: VariantData[];
  requestedVariant?: string;
  children: ReactNode;
}) {
  const initial = initialOverrideAssignment(route, variants, requestedVariant);
  const [assignment, setAssignment] = useState<ExperimentAssignment | undefined>(initial);
  const [ready, setReady] = useState(variants.length === 0);

  useEffect(() => {
    if (!variants.length) return;
    let cancelled = false;
    queueMicrotask(() => {
      let resolved: ExperimentAssignment | undefined;
      try {
        resolved = resolveAndPersistAssignment({
          route,
          variants,
          requestedVariant,
          storage: window.localStorage,
          createVisitorId: anonymousId,
        });
      } catch {
        // Storage can be blocked by the browser. Keep an ephemeral, anonymous split.
        const ephemeralStorage = new Map<string, string>();
        resolved = resolveAndPersistAssignment({
          route,
          variants,
          requestedVariant,
          storage: {
            getItem: (key) => ephemeralStorage.get(key) ?? null,
            setItem: (key, value) => { ephemeralStorage.set(key, value); },
          },
          createVisitorId: anonymousId,
        });
      }
      if (!cancelled) {
        setAssignment(resolved);
        setReady(true);
      }
    });
    return () => { cancelled = true; };
  }, [requestedVariant, route, variants]);

  const activeVariant = assignment ? variants.find((variant) => variant.variant === assignment.variant) : undefined;
  const value = useMemo(() => ({ assignment, activeVariant, ready }), [assignment, activeVariant, ready]);
  return <ExperimentContext.Provider value={value}>{children}</ExperimentContext.Provider>;
}

export function useExperiment() {
  return useContext(ExperimentContext);
}

export function HomeExperimentHero() {
  const { activeVariant, assignment } = useExperiment();
  const isB = assignment?.variant === "B";
  return (
    <div data-experiment={assignment?.experiment_id} data-variant={assignment?.variant}>
      {isB ? <h1>Duas decisões melhores podem mudar <em>os próximos 90 dias.</em></h1> : <h1>Não precisa de mais motivação.<br /><em>Precisa de voltar ao comando.</em></h1>}
      <p className="hero-deck">{activeVariant?.hero_lead || "Uma imersão presencial de dois dias para identificar os padrões que condicionam decisões, recuperar clareza e construir um plano pessoal e profissional executável para os 90 dias seguintes."}</p>
      <div className="hero-actions"><a className="primary-link" href={activeVariant?.destination || "#lista"}>{activeVariant?.primary_cta || "Entrar na lista prioritária"} <ArrowRight /></a><a className="quiet-link" href="#metodo">Conhecer o método <ArrowDown /></a></div>
    </div>
  );
}

function safeDestination(destination: string) {
  return destination.startsWith("/") || destination.startsWith("#") ? destination : undefined;
}

function HeroAction({ label, destination, secondary = false }: { label: string; destination: string; secondary?: boolean }) {
  const safe = safeDestination(destination);
  if (!safe) return <span className={secondary ? "outline-button disabled" : "solid-button disabled"}>{label}</span>;
  return <Link className={secondary ? "outline-button" : "solid-button"} href={safe}>{label}<ArrowRight /></Link>;
}

export function InnerExperimentHero({ hero }: { hero: HeroData }) {
  const { activeVariant, assignment } = useExperiment();
  const h1 = activeVariant?.hero_h1 || hero.h1;
  const lead = activeVariant?.hero_lead || hero.lead;
  const primary = activeVariant ? { label: activeVariant.primary_cta, destination: activeVariant.destination } : hero.primary_cta;
  return (
    <div data-experiment={assignment?.experiment_id} data-variant={assignment?.variant}>
      <p className="eyebrow light"><span />{hero.eyebrow}</p>
      <h1>{h1}</h1>
      {lead && <p className="inner-lead">{lead}</p>}
      {(primary || hero.secondary_cta) && <div className="inner-actions">{primary && <HeroAction {...primary} />}{hero.secondary_cta && <HeroAction {...hero.secondary_cta} secondary />}</div>}
      {activeVariant && <span className="experiment-accessible">Teste {activeVariant.variant}: {activeVariant.hypothesis}</span>}
    </div>
  );
}
