import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Circle, type LucideIcon } from 'lucide-react';
import {
  AURA_COLOR_MEANING,
  AURA_COLOR_NAMES,
  auraFieldGradient,
  type AuraZone,
  type AuraZoneReading,
} from '@/lib/aura/auraField';
import { chakraMeta } from '@/lib/aura/chakraMeta';
import { useLocale, useMessages } from '@/i18n/client';
import type { ChakraType } from '@/lib/aura/types';
import { cn } from '@/lib/cn';

const RAINBOW =
  'conic-gradient(from 200deg, #F97316, #EAB308, #84CC16, #10B981, #14B8A6, #0EA5E9, #6366F1, #A855F7, #EC4899, #EF4444, #F97316)';

// Darkens everything outside an arch rising from the bottom edge.
const DOME =
  'radial-gradient(ellipse 50% 96% at 50% 100%, transparent 88%, rgba(0,0,0,0.85) 97%, #000 100%)';

/** Large soft colour clouds, one per zone, for the instant-film look. */
function filmClouds(zones: AuraZoneReading[]): string {
  const c = Object.fromEntries(zones.map((z) => [z.zone, z.color])) as Record<AuraZone, string>;
  return [
    `radial-gradient(ellipse 85% 50% at 55% 0%, ${c.top} 0%, ${c.top} 25%, transparent 75%)`,
    `radial-gradient(ellipse 65% 85% at 0% 42%, ${c.left} 0%, ${c.left} 25%, transparent 75%)`,
    `radial-gradient(ellipse 65% 85% at 100% 48%, ${c.right} 0%, ${c.right} 25%, transparent 75%)`,
    `radial-gradient(ellipse 90% 50% at 50% 105%, ${c.bottom} 0%, ${c.bottom} 25%, transparent 75%)`,
  ].join(', ');
}

// Keeps the face clear while the clouds wash over everything else.
const FACE_CLEAR = 'radial-gradient(ellipse 20% 17% at 50% 40%, rgba(0,0,0,0.25) 0%, #000 100%)';

/**
 * The person's photo with their aura colours around them.
 * `film` mimics an instant aura camera print; `cloud` is the dark AuraCloud-style dome.
 */
export function AuraPhoto({
  photo,
  zones,
  variant = 'film',
  caption,
  className,
}: {
  photo: string;
  zones: AuraZoneReading[];
  variant?: 'film' | 'cloud';
  /** Printed in the film border, e.g. the person's name. */
  caption?: string;
  className?: string;
}) {
  const t = useMessages().insights;
  if (variant === 'film') {
    const center = zones.find((z) => z.zone === 'center')!.color;
    const clouds = filmClouds(zones);
    return (
      <figure className={cn('rounded-[6px] bg-[#FBFAF7] p-3 pb-12 shadow-float ring-1 ring-black/5 sm:p-4 sm:pb-14', className)}>
        <div className="relative aspect-[3/4] overflow-hidden bg-[#1C1714]">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={photo}
            alt={t.auraPhotoAlt}
            className="absolute inset-0 size-full object-cover"
            style={{ filter: 'contrast(0.9) brightness(1.04) saturate(1.05)' }}
          />
          {/* Colour clouds: a solid wash for body, a screen pass for the light-leak glow */}
          <div
            aria-hidden
            className="absolute -inset-[8%] opacity-70"
            style={{ background: clouds, filter: 'blur(30px) saturate(1.3)', maskImage: FACE_CLEAR, WebkitMaskImage: FACE_CLEAR }}
          />
          <div
            aria-hidden
            className="absolute -inset-[8%] mix-blend-screen opacity-80"
            style={{ background: clouds, filter: 'blur(40px)', maskImage: FACE_CLEAR, WebkitMaskImage: FACE_CLEAR }}
          />
          <div aria-hidden className="absolute inset-0 mix-blend-color opacity-25" style={{ background: clouds }} />
          {/* Halo hugging the head in the core colour */}
          <div
            aria-hidden
            className="absolute inset-0 mix-blend-screen"
            style={{
              background: `radial-gradient(ellipse 30% 25% at 50% 40%, transparent 50%, ${center} 75%, transparent 100%)`,
              filter: 'blur(16px)',
            }}
          />
          {/* Soft film fade */}
          <div
            aria-hidden
            className="absolute inset-0"
            style={{ background: 'radial-gradient(ellipse at 50% 45%, transparent 60%, rgba(20,12,8,0.35) 100%)' }}
          />
        </div>
        <figcaption className="mt-3 text-center text-[11px] tracking-[0.2em] text-[#8A8178] uppercase">
          {caption ?? 'Aura+'}
        </figcaption>
      </figure>
    );
  }

  const field = auraFieldGradient(zones);
  return (
    <div className={cn('rounded-[20px] p-2.5 shadow-float sm:p-3.5', className)} style={{ background: RAINBOW }}>
      <div className="relative aspect-[4/5] overflow-hidden rounded-[12px] bg-black">
        {/* Data URL captured on-device — next/image adds nothing here. */}
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src={photo} alt={t.auraPhotoAlt} className="absolute inset-0 size-full object-cover" />
        {/* Tint the whole scene in the aura colours… */}
        <div aria-hidden className="absolute inset-0 mix-blend-color opacity-75" style={{ background: field }} />
        {/* …and let the field glow, strongest at the edges so the face stays readable. */}
        <div
          aria-hidden
          className="absolute inset-0 mix-blend-screen opacity-80"
          style={{
            background: field,
            maskImage: 'radial-gradient(ellipse 34% 30% at 50% 42%, transparent 40%, #000 100%)',
            WebkitMaskImage: 'radial-gradient(ellipse 34% 30% at 50% 42%, transparent 40%, #000 100%)',
          }}
        />
        <div aria-hidden className="absolute inset-0" style={{ background: DOME }} />
      </div>
    </div>
  );
}

const ZONE_ICON: Record<AuraZone, LucideIcon> = {
  top: ChevronUp,
  left: ChevronLeft,
  center: Circle,
  right: ChevronRight,
  bottom: ChevronDown,
};

/** The five-zone reading that accompanies the aura photo. */
export function AuraZoneLegend({
  zones,
  tone = 'light',
  className,
}: {
  zones: AuraZoneReading[];
  tone?: 'light' | 'dark';
  className?: string;
}) {
  return (
    <ul className={cn('space-y-3', className)}>
      {zones.map((z) => {
        const Icon = ZONE_ICON[z.zone];
        return (
          <li key={z.zone} className="flex gap-3 text-sm leading-relaxed">
            <Icon className="mt-0.5 size-4 shrink-0" strokeWidth={2.5} style={{ color: z.color }} aria-hidden />
            <p className={tone === 'dark' ? 'text-white/75' : 'text-ink-soft'}>
              <span className={cn('font-semibold', tone === 'dark' ? 'text-white' : 'text-ink')}>
                {z.label} ({z.colorName}):
              </span>{' '}
              {z.meaning}
            </p>
          </li>
        );
      })}
    </ul>
  );
}

const COLOR_ORDER: ChakraType[] = ['root', 'sacral', 'solar_plexus', 'heart', 'throat', 'third_eye', 'crown'];

/** Meaning of each aura colour — the person's own colours first, tagged with the zones they appear in. */
export function AuraColorGuide({ zones, className }: { zones: AuraZoneReading[]; className?: string }) {
  const locale = useLocale();
  const t = useMessages().insights;
  const meta = chakraMeta(locale);
  const zonesOf = (c: ChakraType) =>
    zones
      .filter((z) => z.chakra === c)
      .sort((a, b) => Number(b.zone === 'center') - Number(a.zone === 'center'))
      .map((z) => ({ zone: z.zone, label: z.label }));
  const center = zones.find((z) => z.zone === 'center')!.chakra;
  const mine = [center, ...COLOR_ORDER.filter((c) => c !== center && zonesOf(c).length)];
  const others = COLOR_ORDER.filter((c) => !mine.includes(c));

  const row = (c: ChakraType, own: boolean) => (
    <li key={c} className={cn('flex gap-4 py-4 first:pt-0 last:pb-0', !own && 'opacity-60')}>
      <span
        aria-hidden
        className="mt-0.5 size-9 shrink-0 rounded-full"
        style={{
          background: `radial-gradient(circle at 35% 35%, #fff8, ${meta[c].color} 60%)`,
          boxShadow: own ? `0 0 16px ${meta[c].color}88` : undefined,
        }}
      />
      <div className="min-w-0">
        <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm font-semibold text-ink">
          {AURA_COLOR_NAMES[locale][c]}
          {own &&
            zonesOf(c).map((z) => (
              <span key={z.zone} className="rounded-full bg-canvas px-2 py-0.5 text-[11px] font-medium text-muted ring-1 ring-line">
                {z.zone === 'center' ? t.coreColor : z.label}
              </span>
            ))}
        </p>
        <p className="mt-0.5 text-xs font-medium" style={{ color: meta[c].color }}>
          {AURA_COLOR_MEANING[locale][c].keywords}
        </p>
        <p className="mt-1 text-sm leading-relaxed text-ink-soft">{AURA_COLOR_MEANING[locale][c].meaning}</p>
      </div>
    </li>
  );

  return (
    <div className={className}>
      <ul className="divide-y divide-line">{mine.map((c) => row(c, true))}</ul>
      {others.length > 0 && (
        <>
          <p className="eyebrow mt-8 mb-4 text-subtle">{t.otherColors}</p>
          <ul className="divide-y divide-line">{others.map((c) => row(c, false))}</ul>
        </>
      )}
    </div>
  );
}
