'use client';

import { useEffect, useRef, useState } from 'react';

const stops = [
  { name: 'حي النزهة', x: 55, y: 175, status: 'passed' },
  { name: 'حي الروضة', x: 105, y: 150, status: 'passed' },
  { name: 'حي العليا', x: 165, y: 122, status: 'current' },
  { name: 'حي الملز', x: 225, y: 98, status: 'upcoming' },
  { name: 'جامعة الملك سعود', x: 320, y: 68, status: 'upcoming' },
];

const busPath = [
  { x: 55, y: 175 },
  { x: 80, y: 162 },
  { x: 105, y: 150 },
  { x: 135, y: 136 },
  { x: 165, y: 122 },
  { x: 195, y: 110 },
  { x: 225, y: 98 },
  { x: 272, y: 83 },
  { x: 320, y: 68 },
];

interface LiveMapProps {
  currentStopIndex: number;
}

export default function LiveMap({ currentStopIndex }: LiveMapProps) {
  const [busPos, setBusPos] = useState(busPath[currentStopIndex * 2] || busPath[4]);
  const [pulse, setPulse] = useState(true);
  const animRef = useRef<NodeJS.Timeout | null>(null);
  const stepRef = useRef(currentStopIndex * 2);

  useEffect(() => {
    stepRef.current = currentStopIndex * 2;
    setBusPos(busPath[stepRef.current] || busPath[4]);
  }, [currentStopIndex]);

  useEffect(() => {
    animRef.current = setInterval(() => {
      const next = stepRef.current + 1;
      if (next < busPath.length) {
        stepRef.current = next;
        setBusPos(busPath[next]);
      }
    }, 3000);
    return () => { if (animRef.current) clearInterval(animRef.current); };
  }, []);

  const passedPoints = busPath.slice(0, stepRef.current + 1).map(p => `${p.x},${p.y}`).join(' ');
  const upcomingPoints = busPath.slice(stepRef.current).map(p => `${p.x},${p.y}`).join(' ');

  return (
    <div className="relative w-full rounded-2xl overflow-hidden" style={{ height: '240px' }}>
      <img
        src="https://readdy.ai/api/search-image?query=aerial%20top%20view%20satellite%20map%20of%20Riyadh%20Saudi%20Arabia%20city%20streets%20roads%20neighborhoods%20urban%20layout%20clean%20detailed%20cartographic%20style%20neutral%20tones%20showing%20residential%20areas%20and%20university%20campus%20connected%20by%20main%20roads&width=390&height=240&seq=captainlivemap01&orientation=landscape"
        alt="خريطة"
        className="w-full h-full object-cover object-top"
      />
      <div className="absolute inset-0" style={{ background: 'rgba(0,0,0,0.15)' }}></div>

      <svg className="absolute inset-0 w-full h-full" viewBox="0 0 390 240" preserveAspectRatio="none">
        {upcomingPoints && (
          <polyline
            points={upcomingPoints}
            fill="none"
            stroke="rgba(255,255,255,0.4)"
            strokeWidth="4"
            strokeDasharray="8 5"
            strokeLinecap="round"
          />
        )}
        {passedPoints && (
          <polyline
            points={passedPoints}
            fill="none"
            stroke="#10b981"
            strokeWidth="5"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        )}
      </svg>

      {stops.map((stop, i) => (
        <div
          key={i}
          className="absolute"
          style={{
            left: `${(stop.x / 390) * 100}%`,
            top: `${(stop.y / 240) * 100}%`,
            transform: 'translate(-50%, -50%)',
          }}
        >
          <div
            className="w-4 h-4 rounded-full border-2 border-white shadow-md flex items-center justify-center"
            style={{
              background:
                stop.status === 'passed'
                  ? '#10b981'
                  : stop.status === 'current'
                  ? '#f59e0b'
                  : '#94a3b8',
            }}
          >
            {stop.status === 'passed' && (
              <i className="ri-check-line text-white" style={{ fontSize: '8px' }}></i>
            )}
          </div>
          {stop.status === 'current' && (
            <div
              className="absolute inset-0 rounded-full animate-ping"
              style={{ background: 'rgba(245,158,11,0.4)', width: '20px', height: '20px', top: '-2px', left: '-2px' }}
            ></div>
          )}
        </div>
      ))}

      <div
        className="absolute transition-all duration-[2500ms] ease-in-out"
        style={{
          left: `${(busPos.x / 390) * 100}%`,
          top: `${(busPos.y / 240) * 100}%`,
          transform: 'translate(-50%, -50%)',
          zIndex: 10,
        }}
      >
        <div
          className="absolute rounded-full animate-ping"
          style={{ background: 'rgba(16,185,129,0.35)', width: '40px', height: '40px', top: '-6px', left: '-6px' }}
        ></div>
        <div
          className="w-7 h-7 rounded-full flex items-center justify-center shadow-xl border-2 border-white"
          style={{ background: 'linear-gradient(135deg, #059669, #10b981)' }}
        >
          <i className="ri-bus-2-fill text-white" style={{ fontSize: '13px' }}></i>
        </div>
      </div>

      <div className="absolute top-3 right-3 flex items-center gap-1.5 rounded-full px-2.5 py-1.5 shadow-lg" style={{ background: 'rgba(5,150,105,0.92)' }}>
        <span className="w-1.5 h-1.5 bg-white rounded-full animate-pulse"></span>
        <span className="text-white font-bold" style={{ fontSize: '10px', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>مباشر</span>
      </div>

      <div className="absolute bottom-3 left-3 bg-white/95 rounded-xl px-3 py-1.5 shadow-lg flex items-center gap-1.5">
        <i className="ri-map-pin-2-fill text-emerald-600" style={{ fontSize: '12px' }}></i>
        <span className="text-slate-800 font-bold" style={{ fontSize: '11px', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
          {stops[currentStopIndex]?.name || 'حي العليا'}
        </span>
      </div>
    </div>
  );
}
