import { useId } from 'react';
import { CHAKRA_METADATA } from '@/lib/aura/calculator';
import { useMessages } from '@/i18n/client';
import { auraFieldGradient, type AuraZoneReading } from '@/lib/aura/auraField';
import type { ChakraScore, ChakraType } from '@/lib/aura/types';
import { cn } from '@/lib/cn';

/** Height of each chakra on the 200×320 standing figure. */
const Y: Record<ChakraType, number> = {
  crown: 44,
  third_eye: 58,
  throat: 80,
  heart: 108,
  solar_plexus: 132,
  sacral: 152,
  root: 198,
};
const BODY_CHAKRAS: ChakraType[] = ['third_eye', 'throat', 'heart', 'solar_plexus', 'sacral'];

const FRONT_BODY =
  'M95 73 L95 83 C84 85 76 87 72 91 C66 96 64 110 62 128 L56 186 C55 192 60 193 62 188 L70 132 C72 120 74 112 76 108 C78 130 80 150 80 170 C80 200 84 240 86 288 C86 295 96 295 96 288 L98 200 L102 200 L104 288 C104 295 114 295 114 288 C116 240 120 200 120 170 C120 150 122 130 124 108 C126 112 128 120 130 132 L138 188 C140 193 145 192 144 186 L138 128 C136 110 134 96 128 91 C124 87 116 85 105 83 L105 73 Z';

const SIDE_BODY =
  'M95 73 L95 83 C88 86 86 92 86 104 C85 130 90 150 88 172 C86 210 90 250 91 286 C90 292 92 295 98 295 L112 295 C114 293 112 290 106 288 L106 240 C110 210 112 190 112 172 C114 150 117 130 114 108 C112 94 110 86 104 83 L104 73 Z';

function Cone({ x, y, length, half, dir, color }: { x: number; y: number; length: number; half: number; dir: 'up' | 'down' | 'right'; color: string }) {
  const pts =
    dir === 'up'
      ? `${x},${y} ${x - half},${y - length} ${x + half},${y - length}`
      : dir === 'down'
        ? `${x},${y} ${x - half},${y + length} ${x + half},${y + length}`
        : `${x},${y} ${x + length},${y - half} ${x + length},${y + half}`;
  return <polygon points={pts} fill={color} fillOpacity={0.9} />;
}

function Figure({ view, scores }: { view: 'front' | 'side'; scores: ChakraScore }) {
  const id = useId();
  const color = (k: ChakraType) => CHAKRA_METADATA[k].color;
  const crownLen = 10 + scores.crown * 0.22;
  const rootLen = 16 + scores.root * 0.4;

  return (
    <svg viewBox="0 0 200 320" className="relative size-full" aria-hidden>
      <defs>
        <linearGradient id={`${id}-body`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#C7D2FE" stopOpacity="0.75" />
          <stop offset="100%" stopColor="#818CF8" stopOpacity="0.35" />
        </linearGradient>
        <filter id={`${id}-glow`} x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="3" />
        </filter>
      </defs>

      <g fill={`url(#${id}-body)`} stroke="#E0E7FF" strokeOpacity="0.6" strokeWidth="0.8">
        <circle cx={view === 'front' ? 100 : 101} cy="60" r="14" />
        <path d={view === 'front' ? FRONT_BODY : SIDE_BODY} />
        {view === 'side' && <path d="M98 92 C104 120 100 150 104 182" fill="none" strokeOpacity="0.4" />}
      </g>

      <Cone x={100} y={46} length={crownLen} half={4} dir="up" color={color('crown')} />
      <Cone x={100} y={Y.root} length={rootLen} half={5} dir="down" color={color('root')} />

      {BODY_CHAKRAS.map((k) =>
        view === 'front' ? (
          <g key={k}>
            <circle cx="100" cy={Y[k]} r={3 + scores[k] * 0.05} fill={color(k)} filter={`url(#${id}-glow)`} />
            <circle cx="100" cy={Y[k]} r={2 + scores[k] * 0.035} fill={color(k)} />
          </g>
        ) : (
          <Cone
            key={k}
            x={k === 'third_eye' ? 113 : k === 'throat' ? 105 : 113}
            y={Y[k]}
            length={12 + scores[k] * 0.42}
            half={3 + scores[k] * 0.025}
            dir="right"
            color={color(k)}
          />
        ),
      )}
    </svg>
  );
}

/** Front and side views of the body inside its aura field, AuraCloud-style. */
export function AuraBodyMap({
  scores,
  zones,
  className,
}: {
  scores: ChakraScore;
  zones: AuraZoneReading[];
  className?: string;
}) {
  const t = useMessages().insights;
  const field = auraFieldGradient(zones);
  return (
    <div className={cn('grid grid-cols-2 gap-3 sm:gap-4', className)}>
      {(['front', 'side'] as const).map((view) => (
        <figure key={view} className="overflow-hidden rounded-[16px] bg-black p-3 sm:p-5">
          <div className="relative mx-auto aspect-[5/8] max-w-[240px]">
            <div aria-hidden className="absolute inset-0 rounded-[50%] opacity-80 blur-md" style={{ background: field }} />
            <div
              aria-hidden
              className="absolute inset-0 rounded-[50%] ring-1 ring-white/15"
              style={{ background: 'radial-gradient(ellipse at 50% 50%, rgba(255,255,255,0.08), transparent 70%)' }}
            />
            <Figure view={view} scores={scores} />
          </div>
          <figcaption className="mt-2 text-center text-[11px] font-medium tracking-wide text-white/50 uppercase">
            {view === 'front' ? t.front : t.side}
          </figcaption>
        </figure>
      ))}
    </div>
  );
}
