"use client";

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

const formatTel = (phone: string) => {
  if (!phone) return "";
  const clean = phone.replace(/\s+/g, '').replace('+', '00');
  return `00${clean.replace(/^00/, '')}`; // Sikrer 0047 format
};

export default function FacilityDetailView({ facility }: { facility: any }) {
  const activeCourses = (facility.courses || []).filter((c: any) => c.holes && c.holes.length > 0);
  const amenities = facility.amenities || {};
  const nsg = facility.nsg_data || {};
  
  const weatherImg = facility.weather_url?.replace("/graf/dag/", "/innhold/").replace(/\/$/, "") + "/meteogram.svg";
  const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${facility.lat},${facility.lng}`;

  return (
    <main className="min-h-screen bg-[#f1f7ed] pb-20">
      
      {/* HERO SEKSJON */}
      <div className="h-[50vh] min-h-[500px] relative flex flex-col justify-end">
        <img src={facility.image_url || FALLBACK_IMAGE} alt="" className="absolute inset-0 w-full h-full object-cover z-0" />
        <div className="absolute inset-0 bg-gradient-to-t from-[#11280f]/90 via-transparent to-black/20 z-10" />
        
        <div className="relative z-20 max-w-[1400px] mx-auto px-6 w-full pb-12">
          <div className="flex flex-col md:flex-row items-end justify-between gap-8">
            <div>
               <h1 className="text-6xl md:text-8xl font-black text-white mb-2 tracking-tighter drop-shadow-2xl">{facility.name}</h1>
               <p className="text-[#7ca982] uppercase tracking-[0.4em] font-black text-xs md:text-sm mb-6">{facility.city} • {facility.county}</p>
               
               <div className="flex flex-wrap gap-2">
                 {activeCourses.map((c: any) => (
                   <span key={c.id} className="px-4 py-2 rounded-lg text-[10px] font-black uppercase bg-[#7ca982] text-white shadow-xl">
                     {activeCourses.length === 1 ? STATUS_MAP[c.status] || c.status : `${c.name}: ${STATUS_MAP[c.status] || c.status}`}
                   </span>
                 ))}
               </div>
            </div>

            {/* DE 5 IKON-KNAPPENE (Gjeninnført nøyaktig) */}
            <div className="flex gap-2 bg-white/10 backdrop-blur-md p-2 rounded-2xl border border-white/20 shadow-2xl">
               {facility.website_url && <a href={facility.website_url} target="_blank" className="w-12 h-12 bg-white hover:bg-[#7ca982] hover:text-white text-[#11280f] rounded-xl flex items-center justify-center transition-all shadow-md text-xl">🏠</a>}
               {facility.golfbox_booking_url && <a href={facility.golfbox_booking_url} target="_blank" className="w-12 h-12 bg-white hover:bg-[#7ca982] hover:text-white text-[#11280f] rounded-xl flex items-center justify-center transition-all shadow-md text-xl">🕒</a>}
               {facility.golfbox_tournament_url && <a href={facility.golfbox_tournament_url} target="_blank" className="w-12 h-12 bg-white hover:bg-[#7ca982] hover:text-white text-[#11280f] rounded-xl flex items-center justify-center transition-all shadow-md text-xl">🏆</a>}
               <a href={googleMapsUrl} target="_blank" className="w-12 h-12 bg-white hover:bg-[#7ca982] hover:text-white text-[#11280f] rounded-xl flex items-center justify-center transition-all shadow-md text-xl">📍</a>
               {facility.weather_url && <a href={facility.weather_url} target="_blank" className="w-12 h-12 bg-white hover:bg-[#7ca982] hover:text-white text-[#11280f] rounded-xl flex items-center justify-center transition-all shadow-md text-xl">☁️</a>}
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-[1400px] mx-auto px-6 mt-12 grid grid-cols-12 gap-8 items-start">
        
        {/* SIDEBAR */}
        <div className="col-span-12 lg:col-span-3 space-y-6 order-2 lg:order-1">
          <Link href="/" className="flex items-center justify-center bg-white p-5 rounded-2xl shadow-sm font-black text-[#7ca982] border border-gray-100 uppercase text-[10px] tracking-widest hover:bg-[#7ca982] hover:text-white transition-all">← Tilbake til kartet</Link>

          <div className="bg-white p-8 rounded-[2rem] shadow-sm border border-gray-100 font-bold text-sm text-gray-700 space-y-6">
            <h3 className="text-[10px] font-black text-gray-300 uppercase tracking-widest">Kontakt & Adresse</h3>
            <a href={facility.website_url} target="_blank" className="block text-[#7ca982] hover:underline">🌐 Besøk nettsiden</a>
            <a href={`tel:${formatTel(facility.phone)}`} className="block">📞 {facility.phone}</a>
            <a href={`mailto:${facility.email}`} className="block truncate">✉️ {facility.email}</a>
            <div className="pt-4 border-t border-gray-50">
              <a href={googleMapsUrl} target="_blank" className="block hover:text-[#7ca982]">🏠 {facility.address || facility.city}</a>
              <Link href={`/?q=${facility.county}`} className="text-[#7ca982] text-[9px] uppercase font-black hover:underline mt-4 block">Se alle baner i {facility.county} →</Link>
            </div>
          </div>

          {/* VÆR-WIDGET */}
          {facility.weather_url && (
            <div className="bg-white p-4 rounded-[2rem] shadow-sm border border-gray-100 overflow-hidden">
                <h3 className="text-[9px] font-black text-gray-300 uppercase tracking-widest mb-4 ml-4">Værvarsel (48t)</h3>
                <img src={weatherImg} className="w-full scale-110" alt="Vær" />
            </div>
          )}

          {/* ANDRE RESSURSER */}
          <div className="bg-white p-8 rounded-[2rem] shadow-sm border border-gray-100">
             <h3 className="text-[10px] font-black text-gray-300 uppercase tracking-widest mb-6">Andre ressurser</h3>
             <div className="space-y-2">
               {facility.flyfoto_url && <a href={facility.flyfoto_url} target="_blank" className="flex items-center justify-between p-4 bg-gray-50 rounded-xl text-[10px] font-black uppercase text-gray-500 hover:bg-[#7ca982] hover:text-white transition-all"><span>🚁 Flyfoto</span><span>→</span></a>}
               {facility.webcam_url && <a href={facility.webcam_url} target="_blank" className="flex items-center justify-between p-4 bg-gray-50 rounded-xl text-[10px] font-black uppercase text-gray-500 hover:bg-[#7ca982] hover:text-white transition-all"><span>📹 Webkamera</span><span>→</span></a>}
               {facility.baneguide_url && <a href={facility.baneguide_url} target="_blank" className="flex items-center justify-between p-4 bg-gray-50 rounded-xl text-[10px] font-black uppercase text-gray-500 hover:bg-[#7ca982] hover:text-white transition-all"><span>📖 Baneguide</span><span>→</span></a>}
             </div>
          </div>
        </div>

        {/* HOVEDINNHOLD */}
        <div className="col-span-12 lg:col-span-9 space-y-12 order-1 lg:order-2">
          <div className="bg-white p-10 md:p-16 rounded-[3rem] shadow-sm border border-gray-100 leading-relaxed text-xl text-gray-600" dangerouslySetInnerHTML={{ __html: facility.description }} />

          {/* BANEDETALJER + ANDRE TILBUD (Nøyaktig som bildet) */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-8 font-bold text-sm text-gray-700">
             <div className="bg-white p-10 rounded-[2.5rem] shadow-sm border border-gray-100">
                <h3 className="text-2xl font-black mb-8 text-[#11280f] uppercase tracking-tighter">Banen</h3>
                <table className="w-full">
                  <tbody>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Hull:</td><td className="py-4 text-right">{amenities.antall_hull || '--'}</td></tr>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Banetype:</td><td className="py-4 text-right">{facility.banetype || 'Park/Skog'}</td></tr>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Lengde:</td><td className="py-4 text-right">{facility.length || '--'} meter</td></tr>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Sesong:</td><td className="py-4 text-right">{facility.season}</td></tr>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Byggeår:</td><td className="py-4 text-right">{facility.established_year || '--'}</td></tr>
                    <tr><td className="py-4 text-gray-400">Arkitekt:</td><td className="py-4 text-right">{facility.architect || '--'}</td></tr>
                  </tbody>
                </table>
             </div>
             <div className="bg-white p-10 rounded-[2.5rem] shadow-sm border border-gray-100">
                <h3 className="text-2xl font-black mb-8 text-[#11280f] uppercase tracking-tighter">Andre Tilbud</h3>
                <table className="w-full">
                  <tbody>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Drivingrange:</td><td className="py-4 text-right">{amenities.drivingrange ? "Ja" : "Nei"}</td></tr>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Nærspill:</td><td className="py-4 text-right">Ja ✓</td></tr>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Head Pro:</td><td className="py-4 text-right text-orange-500" dangerouslySetInnerHTML={{ __html: amenities.pro }} /></tr>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Proshop:</td><td className="py-4 text-right">Ja</td></tr>
                    <tr className="border-b border-gray-50"><td className="py-4 text-gray-400">Kafé:</td><td className="py-4 text-right text-orange-500" dangerouslySetInnerHTML={{ __html: amenities.kafe }} /></tr>
                    <tr><td className="py-4 text-gray-400">Bilutleie:</td><td className="py-4 text-right">Ja</td></tr>
                  </tbody>
                </table>
             </div>
          </div>

          {/* KART OG VIDEO */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <div className="rounded-[3rem] overflow-hidden shadow-2xl h-96 border-8 border-white bg-gray-100">
                  <iframe width="100%" height="100%" frameBorder="0" src={`https://maps.google.com/maps?q=${facility.lat},${facility.lng}&t=k&z=15&ie=UTF8&iwloc=&output=embed`} />
              </div>
              {facility.video_url && (
                <div className="rounded-[3rem] overflow-hidden shadow-2xl aspect-video bg-black border-8 border-white">
                  <iframe src={facility.video_url} className="w-full h-full" allowFullScreen></iframe>
                </div>
              )}
          </div>

          {/* SCOREKORT */}
          <div className="space-y-12">
            {activeCourses.map((c: any) => <CourseDisplay key={c.id} course={c} />)}
          </div>

          {/* SLOPING TABELLER */}
          <div className="bg-white p-8 rounded-[2.5rem] shadow-sm border border-gray-100">
             <div className="flex justify-between items-center mb-8">
                <h3 className="text-xl font-black uppercase">Slopetabeller</h3>
                <span className="text-[9px] font-black text-gray-400 bg-gray-50 px-3 py-1 rounded-full uppercase">Gyldighet: {facility.gyldig_til_og_med || 'Ukjent'}</span>
             </div>
             <div className="grid grid-cols-1 md:grid-cols-2 gap-12">
                {['herrer', 'damer'].map(gender => (
                  <div key={gender} className="overflow-x-auto">
                    <h4 className="text-[10px] font-black text-[#7ca982] uppercase mb-4 tracking-[0.2em]">{gender}</h4>
                    <table className="w-full text-xs font-bold">
                      <thead>
                        <tr className="text-left text-gray-300 uppercase"><th className="pb-4">Utslag</th><th className="pb-4 text-center">CR</th><th className="pb-4 text-right">Slope</th></tr>
                      </thead>
                      <tbody>
                        {(activeCourses[0]?.tee_boxes?.[gender] || []).map((tee: any, i: number) => (
                          <tr key={i} className="border-t border-gray-50">
                            <td className="py-4 text-gray-800">{tee.navn_utslag || tee.navn_utslag_damer}</td>
                            <td className="py-4 text-center text-[#7ca982]">{tee.baneverdi || tee.baneverdi_damer}</td>
                            <td className="py-4 text-right text-gray-500">{tee.slopeverdi || tee.slopeverdi_damer}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ))}
             </div>
          </div>

          {/* GJESTESPILL & MEDLEMSKAP */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
            <div className="bg-white p-10 rounded-[2.5rem] shadow-sm border border-gray-100">
                <h3 className="text-xl font-black mb-6 uppercase">⛳ Gjestespill</h3>
                <div className="space-y-6">
                    <div>
                      <h4 className="text-[9px] font-black text-gray-300 uppercase mb-3 tracking-widest">Priser</h4>
                      {facility.greenfee?.voksne?.map((g: any, i: number) => (
                        <div key={i} className="flex justify-between py-3 border-b border-gray-50 font-bold text-sm">
                            <span className="text-gray-500">{g.priskategori}</span>
                            <span>kr {g.pris_voksne},-</span>
                        </div>
                      ))}
                      {facility.greenfee?.junior?.map((g: any, i: number) => (
                        <div key={i} className="flex justify-between py-3 border-b border-gray-50 font-bold text-sm">
                            <span className="text-gray-400">{g.priskategori_junior} (Junior)</span>
                            <span className="text-gray-400">kr {g.pris_junior},-</span>
                        </div>
                      ))}
                    </div>
                </div>
                <p className="mt-8 text-[10px] text-gray-400 font-black uppercase">Krav: {facility.guest_requirements}</p>
            </div>

            <div className="bg-white p-10 rounded-[2.5rem] shadow-sm border border-gray-100 flex flex-col">
                <h3 className="text-xl font-black mb-6 uppercase">🤝 Medlemskap</h3>
                <div className="flex-grow space-y-6">
                    <div className="p-8 bg-[#f1f7ed] rounded-[2rem]">
                        <p className="text-[#7ca982] text-[10px] font-black uppercase mb-1">{facility.membership?.standard?.navn || "Standard"}</p>
                        <p className="text-5xl font-black text-gray-800 tracking-tighter">kr {facility.membership?.standard?.pris || '--'},-</p>
                    </div>
                    {facility.membership?.rimeligste?.pris && (
                      <div className="p-6 bg-gray-50 rounded-2xl border border-gray-100">
                          <p className="text-gray-400 text-[9px] font-black uppercase">{facility.membership.rimeligste.navn}</p>
                          <p className="text-2xl font-black text-gray-600">kr {facility.membership.rimeligste.pris},-</p>
                      </div>
                    )}
                </div>
                <a href={facility.membership?.url} target="_blank" className="mt-8 block text-center bg-gray-900 text-white p-5 rounded-2xl font-black uppercase text-xs hover:bg-black transition">Se alle alternativer</a>
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}
