const { useEffect, useMemo, useState } = React;

function useConfig() {
  const [cfg, setCfg] = useState(null);
  useEffect(() => {
    fetch('config.json', { cache: 'no-store' })
      .then(r => r.json())
      .then(setCfg);
  }, []);
  return cfg;
}

function normalizeText(str) {
  return (str || "")
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/\s+/g, " ")
    .trim();
}

// Carga invitados.json (cacheado en memoria) y permite buscar por nombre.
function useTicketsDirectory() {
  const [dir, setDir] = useState({ status: "idle", data: null, error: null });

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        setDir({ status: "loading", data: null, error: null });
        const resp = await fetch('invitados.json', { cache: 'no-store' });
        if (!resp.ok) throw new Error('No se pudo cargar invitados.json');
        const json = await resp.json();
        if (!cancelled) setDir({ status: "ready", data: Array.isArray(json) ? json : [], error: null });
      } catch (e) {
        if (!cancelled) setDir({ status: "error", data: null, error: e });
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const findByName = (name) => {
    if (!dir.data) return null;
    const key = normalizeText(name);
    if (!key) return null;

    // 1) Match exacto normalizado
    const exact = dir.data.find(r => normalizeText(r.nombre) === key);
    if (exact) return exact;

    // 2) Match "contiene" por si el invitado escribe apellidos incompletos
    //const partial = dir.data.find(r => normalizeText(r.nombre).includes(key));
    //return partial || null;
  };

  return { ...dir, findByName };
}

function formatDateLong(iso) {
  const date = new Date(iso);
  const fmt = new Intl.DateTimeFormat('es-MX', {
    weekday: 'long', day: '2-digit', month: 'long', year: 'numeric',
    hour: undefined, minute: undefined, timeZoneName: undefined
  });
  return fmt.format(date);
}

function Countdown({ iso }) {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const target = useMemo(() => new Date(iso), [iso]);
  const diff = Math.max(0, target - now);
  const s = Math.floor(diff / 1000);
  const days = Math.floor(s / 86400);
  const hours = Math.floor((s % 86400) / 3600);
  const minutes = Math.floor((s % 3600) / 60);
  const seconds = s % 60;
  return (
    <div className="grid grid-flow-col auto-cols-max gap-6 text-center">
      {[["Días", days], ["Horas", hours], ["Min", minutes], ["Seg", seconds]].map(([label, val]) => (
        <div key={label} className="p-4">
          <div className="text-3xl md:text-4xl font-semibold tabular-nums text-claro">{String(val).padStart(2,'0')}</div>
          <div className="text-xs uppercase tracking-wider text-claro">{label}</div>
        </div>
      ))}
    </div>
  );
}

function GoogleMapLink({ lat, lng, children }) {
  const href = `https://www.google.com/maps/search/?api=1&query=${lat},${lng}`;
  return <a href={href} target="_blank" rel="noreferrer" className="underline hover:no-underline">{children}</a>
}

function RSVPForm({ cfg, ticketResult }) {
  const [name, setName] = useState("");
  
  const [assist, setAssist] = useState("Sí");
  const [notes, setNotes] = useState("");

  const [guests, setGuests] = useState(0);

 useEffect(() => {
  if (ticketResult) {
    setGuests(ticketResult.adultos + ticketResult.ninos);
  } else {
    setGuests(0);
  }
}, [ticketResult]);

  const message = useMemo(() => {
    return `Hola, soy ${name || "(tu nombre)"}.\n` +
           `Confirmación: ${assist}.` +
           `\nLugar(es): Ceremonia ${cfg.event.ceremony.time}, Recepción ${cfg.event.reception.time}.` +
           `\nAcompañantes: ${guests}.` +
           (notes ? `\nNotas: ${notes}` : "");
  }, [name, guests, assist, notes, cfg]);

  const waLink = useMemo(() => {
    const base = "https://wa.me/";
    const phone = cfg.rsvp.whatsapp_phone_e164.replace("+","");
    const text = encodeURIComponent(message);
    return `${base}${phone}?text=${text}`;
  }, [message, cfg]);

  const mailto = useMemo(() => {
    const subject = encodeURIComponent("Confirmación asistencia boda");
    const body = encodeURIComponent(message);
    return `mailto:${cfg.rsvp.email}?subject=${subject}&body=${body}`;
  }, [message, cfg]);

  function handleSubmit(e) {
    e.preventDefault();
    window.open(waLink, "_blank", "noopener");
  }

  return (
    <form onSubmit={handleSubmit} className="grid gap-4">
      <div>
        <label className="block text-sm font-medium mb-1">Invitado (Nombre)</label>
        <input value={name} onChange={e=>setName(e.target.value)} required
               className="w-full rounded-xl border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-gray-800"/>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">¿Asistirás?</label>
          <select value={assist} onChange={e=>setAssist(e.target.value)} className="w-full rounded-xl border border-gray-300 px-3 py-2">
            <option>Sí</option>
            <option>No</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Lugares reservados</label>
          
          <input type="number" min="0" max="7" value={guests} onChange={e=>setGuests(parseInt(e.target.value||"0"))}
                 readOnly className="w-full rounded-xl border border-gray-300 px-3 py-2"/>
        </div>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Notas (opcional)</label>
        <textarea value={notes} onChange={e=>setNotes(e.target.value)}
                  className="w-full rounded-xl border border-gray-300 px-3 py-2" rows="3" placeholder="Restricciones alimentarias, alergias, etc."/>
      </div>

      <div className="text-sm text-gray-600">{cfg.rsvp.deadline_text}</div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <button type="submit"
                className="rounded-xl px-4 py-3 bg-gray-900 text-white hover:bg-black transition">
          Confirmar por WhatsApp
        </button>
        <a href={mailto} className="rounded-xl px-4 py-3 text-center ring-1 ring-gray-300 hover:bg-gray-50 transition">
          Enviar por Email
        </a>
      </div>

      <details className="text-xs text-gray-500">
        <summary>Ver mensaje</summary>
        <pre className="whitespace-pre-wrap mt-2 p-3 bg-gray-50 rounded-lg">{message}</pre>
      </details>
    </form>
  );
}

function Section({ id, title, children }) {
  return (
    <section id={id} className="py-16 scroll-mt-24">
      <div className="max-w-3xl mx-auto px-6">
        <h2 className="text-3xl md:text-4xl font-semibold elegant mb-6">{title}</h2>
        <div className="hr mb-8" />
        <div className="prose prose-neutral max-w-none">{children}</div>
      </div>
    </section>
  );
}

function App() {
  const cfg = useConfig();
  const ticketsDir = useTicketsDirectory();
  const [ticketName, setTicketName] = useState("");
  const [ticketResult, setTicketResult] = useState(null);
  const [ticketMsg, setTicketMsg] = useState("");
  

  const runTicketSearch = () => {
    const name = ticketName;

    if (ticketsDir.status === "loading") {
      setTicketResult(null);
      setTicketMsg("Cargando lista...");
      return;
    }

    if (ticketsDir.status === "error") {
      setTicketResult(null);
      setTicketMsg("No se pudo cargar la lista de invitados.");
      return;
    }

    const found = ticketsDir.findByName(name);
    if (!found) {
      setTicketResult(null);
      setTicketMsg("No encontramos tu nombre. Verifica la escritura.");
      return;
    }

    const adultos = Number(found.adultos ?? 0);
    const ninos = Number(found.ninos ?? 0);
    setTicketResult({ nombre: found.nombre, adultos, ninos });
    setTicketMsg("");
  };

  if (!cfg) return <div className="p-8">Cargando…</div>;

  const dateLong = formatDateLong(cfg.date_iso);
  const year = new Date(cfg.date_iso).getFullYear();

  return (
    <div className="min-h-screen bg-white text-gray-900 gradient-bg">
      {/* Header */}
      <header className="sticky top-0 z-40 backdrop-blur bg-white/70 border-b border-black/5">
        <div className="max-w-5xl mx-auto px-6 py-3 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <img src="./assets/LogoSinfondo.jpg" alt="Monograma" className="h-8 w-auto" />
            <span className="font-semibold tracking-wide">Gabriela & Diego</span>
          </div>
          <nav className="hidden md:flex gap-6 text-sm">
            <a href="#historia" className="hover:underline">Historia</a>
            <a href="#detalles" className="hover:underline">Detalles</a>
            <a href="#regalos" className="hover:underline">Mesa de regalos</a>
            <a href="#rsvp" className="hover:underline">Confirmar</a>
            <a href="#contacto" className="hover:underline">Contacto</a>
          </nav>
        </div>
      </header>

      {/* Hero */}
      <section className="relative overflow-hidden">
        <div className="bg-foto1 w-full h-[90vh] px-6 py-20 md:py-28">
          <div className="flex flex-col items-center justify-center pt-[25vh]">
            <h1 className="text-7xl text-white">
                {cfg.couple.bride} <span className="text-gray-400">&</span> {cfg.couple.groom}
            </h1>  
            <div className="text-xl font-frank text-claro uppercase tracking-widest mb-2">¡Nos casamos!</div>
          </div>
          
          <div className="grid  sm:grid-cols-1  md:grid-cols-2 lg:grid-cols-3 pt-[15vh]">
            <p className="sm:text-base lg:text-lg uppercase text-claro">{dateLong}</p>
            <div></div>
            <Countdown iso={cfg.date_iso} />
          </div>
        </div>
      </section>

      {/* Historia */}
      <section id="historia"className="relative overflow-hidden">
        <div className="bg-foto2 w-full h-[90vh] px-6 py-20 md:py-28">
          <div className="flex flex-col items-center justify-center relative">
            <div className="text-3xl font-frank text-gray uppercase  mb-2">Nuestra Historia</div>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-1 md:grid-cols-3 lg:grid-cols-3 gap-[5%]  h-[40vh]">
            <div></div>
            <div className="mt-20"><p className="text-gray-700 sm:text-base lg:text-lg leading-relaxed">{cfg.event.story}</p></div>
            <div className="flex items-center justify-center h-[60vh] hidden sm:block">
              <img src="./assets/gabi&diego_belem-2801.jpg" alt="Imagen de Gabriela y Diego" className="w-full h-full object-contain"/>
            </div>
          </div>
        </div>
      </section>
      

      {/* FotoMedio */}  
      <section className="relative overflow-hidden">
        <div className="bg-foto3 w-full h-[90vh] px-6 py-20 md:py-28"></div>
      </section>
      

      {/* Detalles de eventos */}
      <section id="detalles"className="relative overflow-hidden">
        <div className="bg-vacio w-full h-auto px-6 py-20 md:py-28">
          <div className="text-4xl sm:text-4xl lg:text-6xl font-display  text-center mb-2">Nos complace invitarte a ser parte de nuestra historia</div>                    
          <div className="grid sm:grid-cols-1 md:grid-cols-3 gap-8 ">
            {[
              { key: "ceremony", icon: "💒" },
              { key: "reception", icon: "🎉" }
            ].map(({key, icon}) => {
              const ev = cfg.event[key];
              return (
                <div key={key} className="p-6 ">
                  <div className="text-2xl font-frank mb-2">{icon} {ev.title}</div>
                  <div className="text-gray-700">
                    <div className="font-medium">{ev.place_name}</div>
                    <div className="text-sm">{ev.address_hint}</div>
                    <div className="mt-1">Hora: <span className="tabular-nums font-medium">{ev.time}</span></div>
                    <div className="mt-3">
                      <GoogleMapLink lat={ev.lat} lng={ev.lng}>
                       Ver en Google Maps
                      </GoogleMapLink>
                      
                    </div>
                  </div>
                </div>
              );
            })}
            <div className=" p-6">
              <p className="text-2xl font-frank mb-2">💃DressCode🕺</p>
              <p className="text-gray-700 font-medium leading-relaxed">{cfg.event.dress_code}</p>
            </div>
          </div>
          <div className="flex justify-center mt-10">
            <a href="https://calendar.google.com/calendar/render?action=TEMPLATE&text=Boda%20Diego%20y%20Gaby&dates=20260912T170000/20260912T230000&details=Celebramos%20nuestra%20boda&location=Terrazas%20Belvedere,%20De%20Los%20Rosales%2015,%20Hab%20Valle%20Ceylan" target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 rounded-full bg-red-600 px-6 py-3 text-white font-medium hover:bg-red-700 transition">
            Agregar a Google Calendar
            </a>
          </div>
          
        </div>
      </section>

      {/* FotosEnMedio */}  
      <section className="relative overflow-hidden">
        <div className="bg-fotoPuente w-full h-auto px-6 py-20 md:py-28">
          <div className="grid  sm:grid-cols-1  md:grid-cols-2 lg:grid-cols-3 sm:gap-4 md:gap-6 lg:gap-8 p-4">
            <img src="./assets/mirada.jpeg" alt="Imagen Gaby" className="w-3/4 mx-auto h-70 object-cover shadow-md"/>
            <img src="./assets/beso.jpeg" alt="Imagen beso" className="w-3/4 mx-auto h-70 object-cover shadow-md"/>
            <img src="./assets/miradael.jpeg" alt="Imagen Diego" className="w-3/4 mx-auto h-70 object-cover shadow-md"/>
          </div>
        </div>
      </section>
      

      {/* Mesa de regalos */}
      <section id="regalos" className="relative overflow-hidden">
        <div className="bg-vacio w-full h-auto px-6 py-20 md:py-28">
          <div className="grid sm:grid-cols-1 md:grid-cols-2 gap-8 ">
            <div className="flex items-center justify-center h-[60vh]">
              <img src="./assets/gabi&diego_belem-2732.jpg" alt="Imagen sanjeronimo" className="w-full h-full object-contain"/>
            </div>
            <div className="flex flex-col items-center justify-center relative">
              <div className="text-3xl font-frank text-gray uppercase  mb-2">Mesa de regalos</div>
              <div className="mt-20">
                <p className="text-gray-700 sm:text-base lg:text-lg leading-relaxed">{cfg.event.gift_label}</p>
                <div className="grid  sm:grid-cols-1  md:grid-cols-2 lg:grid-cols-2 place-items-center sm:gap-4 md:gap-6 lg:gap-8 p-4">
                  <a href="https://mesaderegalos.liverpool.com.mx/milistaderegalos/51813190" target="_blank" rel="noopener noreferrer">
                    <img src="./assets/liverpool_png.png" alt="LogoLiverpool" />
                  </a>
                  <img src="./assets/banamexCuenta.png" alt="Logobanamex" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Boletos */}
      <section id="boletos" className="relative overflow-hidden">
        <div className="bg-cafe w-full h-auto px-6 py-20 md:py-28">
          <div className="text-3xl font-frank text-stone-300 uppercase  mb-2">
            Con mucho cariño hemos reservado 
          </div>

          {/* Buscador de boletos por invitado */}
          <div className="max-w-xl mx-auto mt-10 text-stone-300">
            <div className="grid sm:grid-cols-1 md:grid-cols-[1fr_auto] gap-3 items-end">
              <div>
                <label className="block text-sm uppercase tracking-wider text-stone-300 mb-2">Escribe tu código</label>
                <input
                  value={ticketName}
                  onChange={(e) => setTicketName(e.target.value)}
                  onKeyDown={(e) => { if (e.key === 'Enter') runTicketSearch(); }}
                  placeholder="Ej. Juan Pérez"
                  autoComplete="name"
                  className="w-full rounded-xl border border-stone-300/30 bg-white/5 px-4 py-3 text-stone-300 placeholder:text-stone-300/60 focus:outline-none focus:ring-2 focus:ring-stone-200"
                />
              </div>
              <button
                type="button"
                onClick={runTicketSearch}
                className="rounded-xl px-5 py-3 bg-stone-200 text-stone-900 hover:bg-white transition"
              >
                Buscar
              </button>
            </div>

            <div className="mt-4 text-center" aria-live="polite">
              {ticketMsg && <div className="text-sm text-stone-300/90">{ticketMsg}</div>}

              {ticketResult && (
                <div className="mt-3 text-2xl font-display">
                  <div className="mb-2 text-5xl md:text-7xl font-display">{ticketResult.nombre}</div>
                  <div className="text-lg font-frank uppercase tracking-wider">
                    {ticketResult.adultos} adulto(s) · {ticketResult.ninos} niño(s)
                  </div>
                </div>
              )}
            </div>
          </div>
          <div className="grid sm:grid-cols-1 md:grid-cols-2 gap-8 ">
            <div className="w-3/4 mx-auto px-4 space-y-8 mt-15">
              <p className="text-stone-300 sm:text-base lg:text-lg leading-relaxed mt-20">{cfg.event.tickets_label}</p>
              <p className="text-stone-300 sm:text-base lg:text-lg leading-relaxed mt-15">{cfg.event.tickets_label2}</p>
            </div>
            <div className="relative w-fit mx-auto">
              <img src="./assets/gabi&diego_belem-2399.jpg" className="w-80"/>
              <img src="./assets/gabi&diego_belem-2453.jpg"  className="absolute top-8 left-[-80px] w-40"/>
            </div>
          </div>
        </div>
      </section>

      {/* Confirmación */}
      <section id="rsvp" className="relative overflow-hidden">
        <div className="bg-vacio w-full h-auto px-6 py-20 md:py-28">
          <div className="text-4xl sm:text-4xl lg:text-6xl font-display  text-center mb-2">Confirma tu asistencia</div>                    
          <div className="grid  sm:grid-cols-1  md:grid-cols-2 lg:grid-cols-3 sm:gap-4 md:gap-6 lg:gap-8 p-4">
            <img src="./assets/gabi&diego_belem-2854.jpg" className="w-3/4 mx-auto h-70 object-cover shadow-md"/>
            <div className="not-prose">
              <RSVPForm cfg={cfg} ticketResult={ticketResult}/>
            </div>
            <img src="./assets/gabi&diego_belem-2839.jpg" className="w-3/4 mx-auto h-70 object-cover shadow-md"/>
          </div>
        </div>
      </section>

      {/* Contacto */}
      <section id="contacto" >
        <div className="bg-cafe w-full h-auto px-6 py-20 md:py-28">
          <div className="text-4xl sm:text-4xl lg:text-6xl font-display text-stone-300 text-center   mb-2">
            Contacto
          </div>
          <div className="flex items-center justify-center h-[60vh]">
              <img src="./assets/gabi&diego_belem-2767.jpg" className="w-full h-full object-contain"/>
          </div>
          <div className="text-stone-300 not-prose mt-20">
            <div className="grid sm:grid-cols-2 gap-6">
              <div>
                <div className="text-sm uppercase tracking-wider text-stone-300">Teléfono</div>
                <a className="underline hover:no-underline" href={`tel:${cfg.rsvp.whatsapp_phone_e164}`}>{cfg.contact.phone_display}</a>
              </div>
              <div>
                <div className="text-sm uppercase tracking-wider text-stone-300">Email</div>
                <a className="underline hover:no-underline" href={`mailto:${cfg.contact.email_display}`}>{cfg.contact.email_display}</a>
              </div>
            </div>
            <div className="mt-8 text-sm text-stone-300">© {year} {cfg.couple.bride} & {cfg.couple.groom}</div>
          </div>
        </div>
      </section>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);