'use client';
import { useRef, useState } from 'react';
import Link from 'next/link';
import type { Template } from '@/lib/templates';
import { TR_VOICES as VOICES, voicesFor } from '@/lib/voices';
import { PLANS, tl } from '@/lib/plans';
import { PlanFeatures } from '../PlanFeatures';
import { PlanPrice } from '../PlanPrice';

/** Kamera rotası: gerçek videodan kareler, haritada göründükleri yere iğnelenmiş. */
const KF = [
  { f: 'v2-bolge', t: '0:01', k: 'Bölge', d: 'Ula ilçesi, Gökova', x: 8, y: 52 },
  { f: 'v2-parsel', t: '0:07', k: 'Parsel', d: 'Tapudaki sınır, iri m² yazısı', x: 24, y: 40 },
  { f: 'v2-mesafe', t: '0:17', k: 'Mesafeler', d: 'Okul, market, eczane; yol üzerinden', x: 40, y: 14 },
  { f: 'v2-ulasim', t: '0:25', k: 'Ulaşım', d: 'Merkez ve havalimanı', x: 56, y: 22 },
  { f: 'v2-tapu', t: '0:33', k: 'Tapu kaydı', d: 'TKGM bilgileri', x: 70, y: 8 },
  { f: 'v2-kapanis', t: '0:36', k: 'Kapanış', d: 'Logonuz, adınız, telefonunuz', x: 84, y: 4 },
];
export function RouteSection() {
  const v = useRef<HTMLVideoElement>(null);
  return (
    <section id="rota" className="relative bg-ink text-white">
      <div className="relative md:h-[860px]" style={{ backgroundImage: 'url(/kareler/rota.jpg)', backgroundSize: 'cover', backgroundPosition: 'center' }}>
        <div className="absolute inset-0 bg-black/35" />
        <div className="relative p-4 md:absolute md:left-6 md:top-8 md:max-w-[460px] md:p-0">
          <h2 className="h-display text-[34px] md:text-[46px]">Kamera bu rotayı izler.</h2>
          <p className="mt-3 text-[15.5px] leading-relaxed text-white/90">Videonun her saniyesi bir konuma bağlı: bölgeden mahalleye, mahalleden parselin köşelerine. Kareler, yukarıdaki parselin gerçek videosundan.</p>
        </div>
        <svg className="pointer-events-none absolute inset-0 hidden h-full w-full md:block" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden>
          <path d="M12.5 65 C 18 61, 23 56, 28.5 53 S 39 30, 44.5 27 S 55 34, 60.5 35 S 70 23, 74.5 21 S 84 17, 88.5 17" fill="none" stroke="#FF6A1F" strokeWidth="0.35" strokeDasharray="1 1" vectorEffect="non-scaling-stroke" style={{ strokeWidth: 2.5 }} />
        </svg>
        <ol className="relative flex snap-x gap-3 overflow-x-auto p-4 md:static md:block md:p-0">
          {KF.map((k) => (
            <li key={k.f} className="w-[132px] shrink-0 snap-start md:absolute md:w-[128px]" style={{ left: `${k.x}%`, top: `${k.y}%` }}>
              <button onClick={() => { const s = parseInt(k.t.split(':')[1]); if (v.current) { v.current.currentTime = s; v.current.play(); v.current.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } }} className="block text-left">
                <img src={`/kareler/${k.f}.jpg`} alt={`${k.t} ${k.k}`} loading="lazy" className="aspect-[9/16] w-full border-2 border-white object-cover" />
                <span className="mt-1 inline-block bg-ink px-1.5 py-0.5 text-[12.5px] font-bold">{k.t} {k.k}</span>
                <span className="block text-[12px] text-white/85 [text-shadow:0_1px_2px_#000]">{k.d}</span>
              </button>
            </li>
          ))}
        </ol>
        <div className="relative px-4 pb-4 md:absolute md:bottom-8 md:right-6 md:p-0">
          <video ref={v} src="/ornekler/minimal.mp4" poster="/ornekler/minimal.jpg" controls playsInline preload="none" className="w-[180px] border-2 border-white bg-ink" />
        </div>
      </div>
    </section>
  );
}

/** Şablonlar: aynı parselin altı videosu, koyu uydu bandında. Üzerine gelince oynar. */
export function TemplateBand({ items }: { items: Template[] }) {
  return (
    <section id="sablonlar" className="relative bg-ink text-white" style={{ backgroundImage: 'url(/kareler/gokova-z17.jpg)', backgroundSize: 'cover', backgroundPosition: 'center' }}>
      <div className="bg-black/70 px-4 py-10 md:px-6 md:py-14">
        <div className="flex flex-wrap items-end justify-between gap-4">
          <div><div className="tag-light">Şablonlar</div><h2 className="h-display mt-1 text-[32px] md:text-[44px]">Aynı parsel, altı görünüm.</h2></div>
          <Link href="/ornekler" className="text-[14px] font-semibold underline underline-offset-4">Tam boy izleyin</Link>
        </div>
        <div className="mt-8 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
          {items.map((t) => (
            <figure key={t.id} className="cursor-pointer" onMouseEnter={(e) => e.currentTarget.querySelector('video')?.play().catch(() => {})} onMouseLeave={(e) => e.currentTarget.querySelector('video')?.pause()} onClick={(e) => { const x = e.currentTarget.querySelector('video'); if (x) { if (x.paused) x.play().catch(() => {}); else x.pause(); } }}>
              <figcaption className="inline-block bg-white px-1.5 py-0.5 text-[12.5px] font-bold uppercase tracking-[0.04em] text-ink">{t.name}</figcaption>
              <video src={`/ornekler/${t.id}.mp4`} poster={`/ornekler/${t.id}.jpg`} muted loop playsInline preload="none" className="block aspect-[9/16] w-full border-2 border-white bg-ink object-cover" />
              <p className="mt-1.5 text-[12.5px] leading-snug text-white/80">{t.tagline}</p>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

/** Sesler: harita lejantı gibi bir liste. */
export function VoiceLegend() {
  const a = useRef<HTMLAudioElement | null>(null); const [on, setOn] = useState('');
  const toggle = (id: string) => {
    if (!a.current) { a.current = new Audio(); a.current.onended = () => setOn(''); }
    if (on === id) { a.current.pause(); setOn(''); return; }
    a.current.src = `/sesler/${id}.mp3?v=3`; a.current.play().then(() => setOn(id)).catch(() => setOn(''));
  };
  return (
    <div className="bg-white">
      <div className="border-b border-ink/15 px-4 py-3"><div className="tag">Lejant · Seslendirme</div><div className="text-[17px] font-bold">{VOICES.length} Türkçe ses, ölçülü sunum dili; yabancı alıcılar için {voicesFor('en').length} İngilizce ses</div></div>
      <ul>
        {VOICES.map((v) => (
          <li key={v.id} className="grid grid-cols-[1fr_auto] items-center gap-3 border-b border-ink/10 px-4 py-2.5 last:border-0">
            <span><b className="text-[15px]">{v.name}</b> <span className="text-[13.5px] text-ink-soft">{v.note}</span></span>
            <button onClick={() => toggle(v.id)} className={`h-8 px-3 text-[13px] font-semibold ${on === v.id ? 'bg-signal text-ink' : 'bg-ink text-white'}`}>{on === v.id ? 'Durdur' : 'Dinle'}</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

/** Fiyatlar: ana sayfadaki sorgu çubuğuyla aynı hücreli dil. */
export function PriceBar() {
  return (
    <div className="cells md:grid-cols-[1fr_1fr_1fr_.9fr]">
      {PLANS.map((p) => (
        <Link key={p.id} href={`/kayit?paket=${p.id}`} className={`cell !justify-start border-b py-4 hover:bg-paper-2 md:border-b-0 md:border-r ${p.featured ? 'bg-signal-soft' : ''}`}>
          <span className="tag">{p.name}{p.featured ? ' · en çok alınan' : ''}</span>
          <span className="mt-1"><PlanPrice plan={p} /></span>
          <span className="mt-1 text-[13.5px] text-ink-soft">{p.credits} video · {p.credits > 1 ? `video başı ${tl(Math.round(p.price / p.credits))}` : 'tek seferlik'}</span>
          <PlanFeatures plan={p} className="mt-3" />
        </Link>
      ))}
      <div className="cell bg-ink py-4 text-white"><span className="tag-light">Koşullar</span><span className="mt-1 text-[13.5px] leading-snug">KDV dahil. Abonelik yok, krediler süresiz. Üretim tamamlanmazsa kredi iade edilir.</span></div>
    </div>
  );
}
