'use client'

import { useMemo } from 'react'
import { motion } from 'framer-motion'
import { useNow, formatTime } from '@/hooks/use-now'

const SIZE = 820
const C = SIZE / 2

/* round to avoid SSR/client float mismatch */
const r3 = (n: number) => Math.round(n * 1000) / 1000

/* polar helper */
function polar(cx: number, cy: number, r: number, angleDeg: number) {
  const a = ((angleDeg - 90) * Math.PI) / 180
  return { x: r3(cx + r * Math.cos(a)), y: r3(cy + r * Math.sin(a)) }
}

/* arc path between two angles */
function arc(r: number, start: number, end: number) {
  const s = polar(C, C, r, end)
  const e = polar(C, C, r, start)
  const large = end - start <= 180 ? 0 : 1
  return `M ${s.x} ${s.y} A ${r} ${r} 0 ${large} 0 ${e.x} ${e.y}`
}

/* donut segment between two radii */
function segment(rOuter: number, rInner: number, start: number, end: number) {
  const so = polar(C, C, rOuter, start)
  const eo = polar(C, C, rOuter, end)
  const si = polar(C, C, rInner, end)
  const ei = polar(C, C, rInner, start)
  const large = end - start <= 180 ? 0 : 1
  return `M ${so.x} ${so.y} A ${rOuter} ${rOuter} 0 ${large} 1 ${eo.x} ${eo.y} L ${si.x} ${si.y} A ${rInner} ${rInner} 0 ${large} 0 ${ei.x} ${ei.y} Z`
}

const DIRECTIONS = [
  { label: 'UTTARA', sub: 'NORTH', angle: 0 },
  { label: 'PURVA', sub: 'EAST', angle: 90 },
  { label: 'DAKSHINA', sub: 'SOUTH', angle: 180 },
  { label: 'PASCHIMA', sub: 'WEST', angle: 270 },
]

const DOSHAS = [
  { label: 'PITTA KALA', time: '10:00 AM – 02:00 PM', color: '#FFD700', start: 30, end: 150 },
  { label: 'KAPHA KALA', time: '06:00 PM – 10:30 PM', color: '#10B981', start: 150, end: 270 },
  { label: 'VATA KALA', time: '02:00 AM – 06:00 AM', color: '#00E5FF', start: 270, end: 390 },
]

const NAK_GLYPHS = '♈♉♊♋♌♍♎♏♐♑♒♓'.split('')

export default function VedicClock() {
  const now = useNow()
  const { time, period } = formatTime(now)

  const nakshatras = useMemo(
    () =>
      Array.from({ length: 12 }).map((_, i) => {
        const angle = (360 / 12) * i
        const p = polar(C, C, 232, angle)
        return { glyph: NAK_GLYPHS[i], x: p.x, y: p.y, angle }
      }),
    [],
  )

  const particles = useMemo(
    () =>
      Array.from({ length: 36 }).map((_, i) => {
        const angle = (360 / 36) * i
        const p = polar(C, C, 300, angle)
        return { x: p.x, y: p.y, delay: (i % 12) * 0.15 }
      }),
    [],
  )

  return (
    <div className="relative aspect-square w-full max-w-[820px]">
      <svg
        viewBox={`0 0 ${SIZE} ${SIZE}`}
        className="h-full w-full overflow-visible"
        aria-label="Vedic cosmic clock"
      >
        <defs>
          <radialGradient id="coreGlow" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="rgba(0,229,255,0.18)" />
            <stop offset="55%" stopColor="rgba(7,20,40,0.65)" />
            <stop offset="100%" stopColor="rgba(3,7,18,0.95)" />
          </radialGradient>
          <linearGradient id="sweep" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#00E5FF" />
            <stop offset="100%" stopColor="#7C3AED" />
          </linearGradient>
          <filter id="soft" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="3" result="b" />
            <feMerge>
              <feMergeNode in="b" />
              <feMergeNode in="SourceGraphic" />
            </feMerge>
          </filter>
        </defs>

        {/* faint guide lines */}
        {DIRECTIONS.map((d) => {
          const a = polar(C, C, 390, d.angle)
          const b = polar(C, C, 250, d.angle)
          return (
            <line
              key={d.label}
              x1={a.x}
              y1={a.y}
              x2={b.x}
              y2={b.y}
              stroke="rgba(0,229,255,0.12)"
              strokeWidth={1}
            />
          )
        })}

        {/* ---------- RING 4: cosmic energy particles ---------- */}
        <g style={{ transformOrigin: 'center', animation: 'spin-slow 60s linear infinite' }}>
          <circle cx={C} cy={C} r={300} fill="none" stroke="rgba(124,58,237,0.18)" strokeWidth={1} />
          {particles.map((p, i) => (
            <circle key={i} cx={p.x} cy={p.y} r={2.2} fill="#00E5FF">
              <animate
                attributeName="opacity"
                values="0.2;1;0.2"
                dur="3s"
                begin={`${p.delay}s`}
                repeatCount="indefinite"
              />
            </circle>
          ))}
        </g>

        {/* ---------- RING 1: outer cosmic ring (directions) ---------- */}
        <g style={{ transformOrigin: 'center', animation: 'spin-slow 220s linear infinite' }}>
          <circle cx={C} cy={C} r={388} fill="none" stroke="rgba(0,229,255,0.22)" strokeWidth={1.5} />
          <circle cx={C} cy={C} r={372} fill="none" stroke="rgba(0,229,255,0.1)" strokeWidth={1} strokeDasharray="2 8" />
        </g>
        {DIRECTIONS.map((d) => {
          const p = polar(C, C, 405, d.angle)
          return (
            <g key={d.label} transform={`translate(${p.x} ${p.y})`}>
              <text
                textAnchor="middle"
                className="font-display"
                fontSize="15"
                letterSpacing="3"
                fill="#F8FAFC"
                style={{ filter: 'drop-shadow(0 0 6px rgba(0,229,255,0.5))' }}
              >
                {d.label}
              </text>
              <text textAnchor="middle" y={16} fontSize="10" letterSpacing="2" fill="#64748b">
                {d.sub}
              </text>
            </g>
          )
        })}

        {/* ---------- RING 2: dosha ring ---------- */}
        <g style={{ transformOrigin: 'center', animation: 'spin-slow 320s linear infinite reverse' }}>
          {DOSHAS.map((d) => (
            <g key={d.label}>
              <path d={segment(348, 286, d.start, d.end)} fill={d.color} opacity={0.06} />
              <path d={arc(348, d.start + 2, d.end - 2)} fill="none" stroke={d.color} strokeWidth={2} opacity={0.55} strokeLinecap="round" />
            </g>
          ))}
          {DOSHAS.map((d) => {
            const mid = (d.start + d.end) / 2
            const flip = mid > 90 && mid < 270
            const p = polar(C, C, 317, mid)
            return (
              <g key={`lbl-${d.label}`} transform={`translate(${p.x} ${p.y}) rotate(${flip ? mid + 180 : mid})`}>
                <text textAnchor="middle" className="font-display" fontSize="13" letterSpacing="2" fill={d.color}>
                  {d.label}
                </text>
                <text textAnchor="middle" y={15} fontSize="9" letterSpacing="1" fill="rgba(248,250,252,0.5)">
                  {d.time}
                </text>
              </g>
            )
          })}
        </g>

        {/* ---------- RING 3: nakshatra zodiac glyphs ---------- */}
        <g style={{ transformOrigin: 'center', animation: 'spin-slow 180s linear infinite' }}>
          <circle cx={C} cy={C} r={262} fill="none" stroke="rgba(255,215,0,0.14)" strokeWidth={1} />
          <circle cx={C} cy={C} r={202} fill="none" stroke="rgba(0,229,255,0.14)" strokeWidth={1} />
          {nakshatras.map((n, i) => (
            <text
              key={i}
              x={n.x}
              y={n.y}
              dy="0.35em"
              textAnchor="middle"
              fontSize="22"
              fill={i % 2 === 0 ? '#FFD700' : '#00E5FF'}
              opacity={0.8}
              style={{ filter: 'drop-shadow(0 0 4px currentColor)' }}
            >
              {n.glyph}
            </text>
          ))}
        </g>

        {/* rotating sweep arc */}
        <g style={{ transformOrigin: 'center', animation: 'spin-slow 8s linear infinite' }}>
          <path d={arc(195, 200, 320)} fill="none" stroke="url(#sweep)" strokeWidth={4} strokeLinecap="round" filter="url(#soft)" />
        </g>

        {/* ---------- center holographic core ---------- */}
        <circle cx={C} cy={C} r={188} fill="url(#coreGlow)" stroke="rgba(0,229,255,0.3)" strokeWidth={1.5} />
        <circle cx={C} cy={C} r={188} fill="none" stroke="rgba(0,229,255,0.5)" strokeWidth={1} strokeDasharray="1 14" />
      </svg>

      {/* ---------- center HTML overlay (crisp text) ---------- */}
      <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
        <div className="flex w-[46%] flex-col items-center text-center">
          <span className="font-display text-[0.6rem] tracking-cosmic text-muted-foreground sm:text-xs">
            CURRENT TIME
          </span>
          <div className="mt-1 flex items-baseline gap-1">
            <motion.span
              key={time}
              className="font-display text-3xl font-bold tabular-nums text-white text-glow-primary sm:text-4xl md:text-5xl"
            >
              {time}
            </motion.span>
            <span className="font-display text-sm text-primary sm:text-base">{period}</span>
          </div>

          <div className="mt-3 h-px w-3/4 bg-gradient-to-r from-transparent via-primary/50 to-transparent" />

          <span className="mt-3 text-sm tracking-widest text-muted-foreground">
            SHUKLA PAKSHA
          </span>
          <span className="font-display text-lg font-semibold tracking-wide text-white sm:text-xl">
            EKADASHI TITHI
          </span>
          <span className="text-sm tracking-widest text-slate-300">ROHINI NAKSHATRA</span>

          <span className="mt-2 font-display text-base font-bold tracking-widest text-danger text-glow-danger">
            PITTA KALA
          </span>

          <div className="mt-3 h-px w-1/2 bg-gradient-to-r from-transparent via-secondary/50 to-transparent" />
          <span className="mt-2 text-xs tracking-widest text-slate-300">2nd PRAHAR</span>
          <span className="text-[0.7rem] tracking-wide text-muted-foreground">
            10:30 AM – 01:30 PM
          </span>
        </div>
      </div>

      {/* pulsing glow under clock */}
      <div
        className="pointer-events-none absolute left-1/2 top-1/2 -z-10 h-[60%] w-[60%] -translate-x-1/2 -translate-y-1/2 rounded-full"
        style={{
          background: 'radial-gradient(circle, rgba(0,229,255,0.22), transparent 70%)',
          animation: 'pulse-glow 5s ease-in-out infinite',
        }}
      />
    </div>
  )
}
