"use client";
/**
 * TEE OFF DETAIL VIEW - COMPLETE v3.7 (STABLE)
 * ---------------------------------------------------------------------------
 * REGEL 1: Garanterer parsing av JSON-data (courses, amenities, greenfee osv).
 * REGEL 2: Beholder 22/78 layout og alle visuelle seksjoner (Kart, Video, Priser).
 * REGEL 3: Viser KUN bilder fra klubbens eget galleri i slideren.
 * REGEL 4: Bruker monokrome ikoner (#11280f) og oransje lenker (#ff5722).
 * ---------------------------------------------------------------------------
 */

import { useState, useEffect } from 'react';
import { STATUS_MAP, FALLBACK_IMAGE } from "@/config/constants";
import Link from 'next/link';
import CourseDisplay from './CourseDisplay';

// --- MONOKROME SVG IKONER ---
const Icon = ({ children, className = "w-5 h-5" }: { children: React.ReactNode, className?: string }) => (
  <svg className={`${className} flex-shrink-0`} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">{children}</svg>
);

const ICONS = {
  web: <><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" /><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" /></>,
  phone: <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" />,
  mail: <><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" /><polyline points="22,6 12,13 2,6" /></>,
  map: <><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" /></>,
  booking: <><rect x="3" y="4" width="18" height="18" rx="2" ry="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /></>,
  trophy: <><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" /><path d="M18 9h1.5a2.5 2.5 0 0 1 0-5H18" /><path d="M4 22h16" /><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22" /><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22" /><path d="M18 2H6v7a6 6 0 0 0 12 0V2z" /></>,
  guide: <><polygon points="3 6 9 3 15 6 21 3 21 18 15 21 9 18 3 21" /><line x1="9" y1="3" x2="9" y2="18" /><line x1="15" y1="6" x2="15" y2="21" /></>,
  camera: <><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" /><circle cx="12" cy="13" r="4" /></>,
  webcam: <><circle cx="12" cy="12" r="8" /><circle cx="12" cy="12" r="3" /><line x1="12" y1="2" x2="12" y2="4" /><line x1="12" y1="20" x2="12" y2="22" /><line x1="20" y1="12" x2="22" y2="12" /><line x1="2" y1="12" x2="4" y2="12" /></>,
  weather: <path d="M17.5 19c2.5 0 4.5-2 4.5-4.5 0-2.4-1.8-4.3-4.2-4.5C17.3 6.1 13.5 3 9 3 5.2 3 2 5.8 2 9.5a5.5 5.5 0 0 0 5.5 5.5h10" />,
  facebook: <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />,
  instagram: <><rect x="2" y="2" width="20" height="20" rx="5" ry="5" /><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" /><line x1="17.5" y1="6.5" x2="17.51" y2="6.5" /></>
};

export default function FacilityDetailView({ facility }: { facility: any }) {
  const [showBackToTop, setShowBackToTop] = useState(false);
  const [currentSlide, setCurrentSlide] = useState(0);

  // --- DATA RECOVERY LOGIKK (Fikser krasj fra API-strenger) ---
  const parseJson = (val: any, fallback: any) => {
    if (!val) return fallback;
    if (typeof val === 'object') return val;
    try { return JSON.parse(val); } catch (e) { return fallback; }
  };

  const rawCourses = parseJson(facility.courses, []);
  const activeCourses = Array.isArray(rawCourses) ? rawCourses.filter((c: any) => c.holes && (typeof c.holes === 'string' || c.holes.length > 0)) : [];
  const amenities = parseJson(facility.amenities, {});
  const gallery = parseJson(facility.gallery, [facility.image_url || FALLBACK_IMAGE]);
  const greenfee = parseJson(facility.greenfee, []);
  const shotzoom = parseJson(facility.shotzoom, []);
  
  const linkClass = "text-orange-600 hover:underline transition-colors font-bold";

  useEffect(() => {
    if (gallery.length <= 1) return;
    const timer = setInterval(() => setCurrentSlide((p) => (p + 1) % gallery.length), 5000);
    return () => clearInterval(timer);
  }, [gallery.length]);

  useEffect(() => {
    const handleScroll = () => setShowBackToTop(window.scrollY > 500);
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const scrollTo = (id: string) => {
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.pageYOffset - 80, behavior: 'smooth' });
  };

  const formatDate = (d: string) => d ? new Date(d).toLocaleDateString('nb-NO', { day: 'numeric', month: 'long', year: 'numeric' }) : null;
  const weatherImg = facility.weather_url?.replace("/graf/dag/", "/innhold/").replace(/\/$/, "") + "/meteogram.svg";

  return (
    <main className="min-h-screen bg-[#f1f7ed] pb-20 relative font-sans text-[#11280f]">
      
      {/* GALLERI SLIDER */}
      <div className="h-[55vh] min-h-[450px] relative overflow-hidden bg-[#11280f]">
        {gallery.map((img: string, i: number) => (
            <img key={i} src={img} className={`absolute inset-0 w-full h-full object-cover transition-opacity duration-1000 ${i === currentSlide ? 'opacity-100 z-10' : 'opacity-0 z-0'}`} alt="" />
        ))}
        <div className="absolute inset-0 bg-gradient-to-t from-[#11280f]/90 via-transparent to-black/10 z-20" />
        
        {/* BANESTATUS BADGES */}
        <div className="absolute top-8 right-8 z-40 flex flex-col items-end gap-1">
            <div className="flex flex-wrap justify-end gap-2">
                {activeCourses.map((c: any) => (
                    <span key={c.id} className="px-3 py-1.5 rounded-lg text-[10px] font-black uppercase bg-[#7ca982] text-white shadow-xl">{STATUS_MAP[c.status] || c.status}</span>
                ))}
            </div>
            {facility.status_updated_at && <span className="text-white/60 text-[10px] uppercase font-bold tracking-widest mt-1">Sist oppdatert: {formatDate(facility.status_updated_at)}</span>}
        </div>

        {/* HURTIGKNAPPER */}
        <div className="absolute bottom-8 right-8 z-40 flex gap-2.5 bg-black/30 backdrop-blur-md p-2 rounded-2xl border border-white/10 shadow-2xl">
            {facility.website_url && <a href={facility.website_url} target="_blank" className="w-9 h-9 bg-white rounded-xl flex items-center justify-center text-[#11280f] hover:text-orange-600 transition-all"><Icon children={ICONS.web} /></a>}
            {facility.golfbox_booking_url && <a href={facility.golfbox_booking_url} target="_blank" className="w-9 h-9 bg-white rounded-xl flex items-center justify-center text-[#11280f] hover:text-orange-600 transition-all"><Icon children={ICONS.booking} /></a>}
            {facility.golfbox_tournament_url && <a href={facility.golfbox_tournament_url} target="_blank" className="w-9 h-9 bg-white rounded-xl flex items-center justify-center text-[#11280f] hover:text-orange-600 transition-all"><Icon children={ICONS.trophy} /></a>}
            <a href={`https://www.google.com/maps/search/?api=1&query=${facility.lat},${facility.lng}`} target="_blank" className="w-9 h-9 bg-white rounded-xl flex items-center justify-center text-[#11280f] hover:text-orange-600 transition-all"><Icon children={ICONS.map} /></a>
            {facility.weather_url && <a href={facility.weather_url} target="_blank" className="w-9 h-9 bg-white rounded-xl flex items-center justify-center text-[#11280f] hover:text-orange-600 transition-all"><Icon children={ICONS.weather} /></a>}
        </div>

        <div className="relative z-30 max-w-[1200px] mx-auto px-6 w-full h-full flex flex-col justify-end pb-12">
            {facility.logo_url && <div className="hidden md:block mb-8 w-24 h-24 bg-white p-2 rounded-2xl shadow-2xl border-4 border-white/20 overflow-hidden"><img src={facility.logo_url} className="w-full h-full object-contain" alt="" /></div>}
            <h1 className="text-5xl md:text-8xl font-black text-white mb-3 tracking-tighter drop-shadow-2xl">{facility.name}</h1>
            <p className="text-[#7ca982] uppercase tracking-[0.4em] font-black text-xs md:text-sm pl-1">{facility.county} • {facility.city}</p>
        </div>
      </div>

      {/* NAVIGASJON */}
      <nav className="sticky top-0 z-50 bg-white/95 backdrop-blur-md border-b border-gray-100 shadow-sm overflow-hidden">
        <div className="max-w-[1200px] mx-auto px-6 flex justify-between md:justify-start gap-4 md:gap-10 h-16 items-center text-[10px] font-black uppercase tracking-widest text-gray-400">
          <button onClick={() => scrollTo('intro')}>Info</button>
          <button onClick={() => scrollTo('weather')}>Vær</button>
          <button onClick={() => scrollTo('details')}>Detaljer</button>
          <button onClick={() => scrollTo('map')}>Kart</button>
          <button onClick={() => scrollTo('prices')}>Priser</button>
          <button onClick={() => scrollTo('scorecards')}>Scorekort</button>
        </div>
      </nav>

      <div className="max-w-[1200px] mx-auto px-0 md:px-6 space-y-4 md:space-y-12 mt-0 md:mt-12">
        
        {/* INTRO SEKSJON */}
        <section id="intro" className="flex flex-col lg:flex-row gap-0 md:gap-8 items-stretch">
          <div className="lg:w-[22%] bg-white p-10 md:rounded-[3rem] shadow-sm flex flex-col border-b md:border-none">
             <h3 className="text-[10px] font-black text-gray-300 uppercase tracking-widest mb-8">Kontakt & Adresse</h3>
             <div className="space-y-6 text-sm font-bold">
                <a href={facility.website_url} target="_blank" className={`flex items-center gap-4 ${linkClass}`}><Icon children={ICONS.web} /> Besøk nettsiden</a>
                <a href={`tel:${facility.phone}`} className="flex items-center gap-4"><Icon children={ICONS.phone} /> {facility.phone || 'Ikke oppgitt'}</a>
                <a href={`mailto:${facility.email}`} className="flex items-center gap-4 truncate"><Icon children={ICONS.mail} /> {facility.email || 'Ikke oppgitt'}</a>
                <a href={`https://www.google.com/maps/search/?api=1&query=${facility.lat},${facility.lng}`} target="_blank" className="flex items-start gap-4 leading-tight hover:text-orange-600 transition-colors pt-2"><Icon children={ICONS.map} className="mt-1" /> <span>{facility.address}<br/>{facility.city}</span></a>
             </div>
          </div>
          <div className="lg:w-[78%] bg-white p-10 md:p-16 md:rounded-[3rem] shadow-sm border-b md:border-none">
             {facility.footnote && <div className="mb-8 pb-8 border-b border-gray-50 italic text-gray-400 text-lg leading-relaxed font-serif">{facility.footnote}</div>}
             <div className="leading-relaxed text-lg md:text-xl text-gray-600" dangerouslySetInnerHTML={{ __html: facility.description || 'Ingen beskrivelse tilgjengelig.' }} />
          </div>
        </section>

        {/* VÆR SEKSJON */}
        <section id="weather" className="bg-white p-0 md:p-12 md:rounded-[3rem] shadow-sm border-b md:border-none overflow-hidden text-center">
           <h3 className="text-[10px] font-black text-gray-300 uppercase tracking-[0.2em] py-8 md:py-0 md:mb-10 flex items-center justify-center gap-3"><Icon children={ICONS.weather} /> Vær for {facility.name}</h3>
           <div className="w-full flex justify-center px-4 md:px-0">
              {facility.weather_url ? ( <img src={weatherImg} className="w-full h-auto block max-w-5xl" alt="Vær" /> ) : <p className="text-center py-24 text-gray-300 italic text-sm">Værvarsel ikke tilgjengelig</p>}
           </div>
        </section>

        {/* DETALJER SEKSJON */}
        <section id="details" className="flex flex-col lg:flex-row gap-4 md:gap-8">
           <div className="lg:w-[22%] bg-white p-10 md:rounded-[3rem] shadow-sm border-b md:border-none">
              <h3 className="text-lg font-black mb-8 uppercase tracking-tighter">Ressurser</h3>
              <div className="space-y-2.5 text-[#11280f]">
                 {facility.golfbox_booking_url && <a href={facility.golfbox_booking_url} target="_blank" className="flex justify-between items-center p-4 bg-gray-50 rounded-2xl text-[11px] font-black uppercase hover:bg-orange-600 hover:text-white transition-all"><span><Icon children={ICONS.booking} className="inline mr-3" /> Book Starttid</span><span>→</span></a>}
                 {facility.baneguide_url && <a href={facility.baneguide_url} target="_blank" className="flex justify-between items-center p-4 bg-gray-50 rounded-2xl text-[11px] font-black uppercase hover:bg-orange-600 hover:text-white transition-all"><span><Icon children={ICONS.guide} className="inline mr-3" /> Baneguide</span><span>→</span></a>}
                 {shotzoom.map((sz: any, i: number) => (
                    <a key={i} href={sz.shotzoom_url} target="_blank" className="flex justify-between items-center p-4 bg-gray-50 rounded-2xl text-[11px] font-black uppercase text-orange-600 border border-orange-50 shadow-sm"><span>📊 Statistikk: {sz.shotzoom_beskrivelse?.replace('&nbsp;', ' ')}</span><span>→</span></a>
                 ))}
              </div>
           </div>

           <div className="lg:w-[78%] grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-8 text-sm font-bold text-gray-700">
                <div className="bg-white p-10 md:rounded-[3rem] shadow-sm">
                    <h3 className="text-lg font-black mb-8 uppercase tracking-tighter text-[#11280f]">Banen</h3>
                    <div className="space-y-5">
                        <div className="flex justify-between border-b border-gray-50 pb-3"><span>Hull:</span><span>{amenities.antall_hull || '--'}</span></div>
                        <div className="flex justify-between border-b border-gray-50 pb-3"><span>Banetype:</span><span>{facility.banetype || 'Park/Skog'}</span></div>
                        <div className="flex justify-between"><span>Arkitekt:</span><span className="text-right ml-4">{facility.architect || '--'}</span></div>
                    </div>
                </div>
                <div className="bg-white p-10 md:rounded-[3rem] shadow-sm">
                    <h3 className="text-lg font-black mb-8 uppercase tracking-tighter text-[#11280f]">Fasiliteter</h3>
                    <div className="space-y-5">
                        <div className="flex justify-between border-b border-gray-50 pb-3"><span>Drivingrange:</span><span>{amenities.drivingrange || 'Nei'}</span></div>
                        <div className="flex justify-between border-b border-gray-50 pb-3"><span>Proshop:</span><span dangerouslySetInnerHTML={{ __html: amenities.proshop ? String(amenities.proshop).replace('Ja', `<span class="${linkClass}">Ja</span>`) : 'Nei' }} /></div>
                        <div className="flex justify-between border-b border-gray-50 pb-3"><span>Simulator:</span><span dangerouslySetInnerHTML={{ __html: amenities.simulator ? String(amenities.simulator).replace('Ja', `<span class="${linkClass}">Ja</span>`) : 'Nei' }} /></div>
                    </div>
                </div>
           </div>
        </section>

        {/* KART SEKSJON */}
        <section id="map" className="space-y-6">
           <h2 className="text-3xl md:text-4xl font-black uppercase tracking-tighter flex items-center gap-5 ml-6 md:ml-0">Kart <span className="h-1 flex-grow bg-gray-100 rounded-full" /></h2>
           <div className="w-full md:rounded-[3rem] overflow-hidden shadow-xl h-[450px] md:h-[650px] border-y-4 md:border-[12px] border-white bg-gray-100"><iframe width="100%" height="100%" style={{ border: 0 }} src={`https://maps.google.com/maps?q=${facility.lat},${facility.lng}&t=k&z=15&ie=UTF8&iwloc=&output=embed`} allowFullScreen /></div>
        </section>

        {/* PRISER SEKSJON */}
        <section id="prices" className="grid grid-cols-1 lg:grid-cols-2 gap-0 md:gap-8">
           <div className="bg-white p-10 md:p-14 md:rounded-[3rem] shadow-sm">
              <h3 className="text-2xl font-black mb-10 uppercase tracking-tighter">⛳ Gjestespill</h3>
              <div className="space-y-2">
                  {greenfee.length > 0 ? (
                    greenfee.map((g: any, i: number) => (
                      <div key={i} className="flex justify-between py-4 border-b border-gray-50 font-bold text-lg"><span>{g.priskategori}</span><span>kr {g.pris_voksne || '--'},-</span></div>
                    ))
                  ) : <p className="text-gray-400 italic py-6">Ingen priser funnet.</p>}
              </div>
           </div>
           
           <div className="bg-white p-10 md:p-14 md:rounded-[3rem] shadow-sm flex flex-col justify-between">
              <div>
                <h3 className="text-2xl font-black mb-10 uppercase tracking-tighter">💛 Medlemskap</h3>
                <div className="bg-[#f1f7ed] p-12 md:rounded-[2.5rem] mb-8 text-center border border-[#7ca982]/10">
                    <p className="text-6xl font-black text-[#11280f]">kr {facility.standard_medlemskap || '--'},-</p>
                </div>
              </div>
              <a href={facility.medlemskap_url} target="_blank" className="mt-10 block w-full text-center bg-[#11280f] text-white p-7 rounded-2xl font-black uppercase text-xs tracking-widest shadow-xl">Se alle alternativer</a>
           </div>
        </section>

        {/* SCOREKORT SEKSJON */}
        <section id="scorecards" className="pt-10 space-y-20 overflow-hidden">
           <h3 className="text-center text-3xl md:text-5xl font-black uppercase tracking-tighter">Scorekort</h3>
           <div className="w-full flex flex-col items-center gap-20">
                {activeCourses.map((c: any) => (
                    <div key={c.id} className="w-full overflow-x-auto md:overflow-visible no-scrollbar">
                         <div className="min-w-[800px] md:min-w-0"><CourseDisplay course={c} /></div>
                    </div>
                ))}
           </div>
        </section>
      </div>

      {showBackToTop && ( <button onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })} className="fixed bottom-8 right-8 w-14 h-14 bg-[#11280f] text-white rounded-full shadow-2xl flex items-center justify-center text-2xl z-[100] border-4 border-white/20">↑</button> )}
    </main>
  );
}