/*
División Táctica MEIS - Medioambiente
Single-file React component (default export) using Tailwind CSS.

How to use:
1. Create a React app (Vite/CRA) with Tailwind configured.
2. Paste this component into a file like src/App.jsx and import in index.jsx.
3. Tailwind must be available. The component uses shadcn/ui and lucide-react imports optionally; if not available remove those imports or replace with plain elements.

Features:
- Responsive landing page for División Táctica MEIS Medioambiente
- Hero, misión, proyectos, alert/report form (saves to localStorage), mapa embebido, contacto
- Panel simple (cliente) para ver alertas guardadas en localStorage

Notes:
- Backend endpoints (API) are stubbed as comments; connect to your server to persist alerts.
- The contact form currently uses mailto: fallback. Replace with POST to your server for production.
*/

import React, { useState, useEffect } from "react";
import { MapPin, AlertCircle, Mail, Phone } from "lucide-react";

export default function DivisionTacticaMeis() {
  const [alerts, setAlerts] = useState(() => {
    try {
      return JSON.parse(localStorage.getItem("meis_alerts") || "[]");
    } catch (e) {
      return [];
    }
  });

  const [form, setForm] = useState({
    nombre: "",
    telefono: "",
    ubicacion: "",
    mensaje: "",
    categoria: "Incidente Ambiental",
  });

  useEffect(() => {
    localStorage.setItem("meis_alerts", JSON.stringify(alerts));
  }, [alerts]);

  function handleChange(e) {
    const { name, value } = e.target;
    setForm((s) => ({ ...s, [name]: value }));
  }

  function sendAlert(e) {
    e.preventDefault();
    const nueva = {
      id: Date.now(),
      ...form,
      fecha: new Date().toISOString(),
      estado: "Pendiente",
    };
    setAlerts((a) => [nueva, ...a]);
    setForm({ nombre: "", telefono: "", ubicacion: "", mensaje: "", categoria: "Incidente Ambiental" });

    // TODO: En producción, enviar POST a tu API:
    // fetch('/api/alerts', { method: 'POST', body: JSON.stringify(nueva'), headers:{'Content-Type':'application/json'} })
  }

  function markAttended(id) {
    setAlerts((a) => a.map(x => x.id===id ? {...x, estado:'Atendida'} : x));
  }

  function removeAlert(id) {
    setAlerts((a) => a.filter(x => x.id !== id));
  }

  return (
    <div className="min-h-screen bg-gray-50 text-slate-900">
      <header className="bg-gradient-to-r from-emerald-600 to-green-500 text-white p-6 shadow-md">
        <div className="max-w-6xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="w-14 h-14 bg-white rounded-full flex items-center justify-center text-green-600 font-bold">MEIS</div>
            <div>
              <h1 className="text-2xl font-bold">División Táctica MEIS</h1>
              <p className="text-sm opacity-90">Medioambiente & Respuesta Rápida</p>
            </div>
          </div>
          <nav className="hidden md:flex gap-4 items-center">
            <a href="#mision" className="hover:underline">Misión</a>
            <a href="#proyectos" className="hover:underline">Proyectos</a>
            <a href="#alertas" className="hover:underline">Reportar</a>
            <a href="#contacto" className="hover:underline">Contacto</a>
          </nav>
        </div>
      </header>

      <main className="max-w-6xl mx-auto p-6">
        {/* Hero */}
        <section className="grid md:grid-cols-2 gap-8 items-center mt-8">
          <div>
            <h2 className="text-4xl font-extrabold">Protegiendo el entorno, actuando con táctica.</h2>
            <p className="mt-4 text-lg opacity-90">La División Táctica MEIS Medioambiente coordina respuesta rápida, monitoreo y acciones preventivas para eventos ambientales. Únete, reporta y colabora con nosotros.</p>
            <div className="mt-6 flex gap-3">
              <a href="#alertas" className="px-5 py-3 rounded-lg bg-emerald-600 text-white font-medium">Reportar Incidente</a>
              <a href="#proyectos" className="px-5 py-3 rounded-lg border border-emerald-600 text-emerald-600">Ver Proyectos</a>
            </div>
          </div>

          <div className="bg-white rounded-2xl shadow p-6">
            <h3 className="font-semibold mb-3 flex items-center gap-2"><AlertCircle size={18}/> Estado rápido</h3>
            <ul className="space-y-2">
              <li className="flex justify-between"><span>Incidentes abiertos</span><strong>{alerts.filter(a => a.estado==='Pendiente').length}</strong></li>
              <li className="flex justify-between"><span>Incidentes atendidos</span><strong>{alerts.filter(a => a.estado==='Atendida').length}</strong></li>
              <li className="flex justify-between"><span>Total reportes</span><strong>{alerts.length}</strong></li>
            </ul>
            <p className="mt-4 text-sm opacity-80">Este panel es cliente-side. En producción conecta con tu panel de alertas central (CPanel) para ver en tiempo real con mapas y audio.</p>
          </div>
        </section>

        {/* Misión */}
        <section id="mision" className="mt-12 bg-white p-6 rounded-2xl shadow">
          <h3 className="text-2xl font-bold">Misión</h3>
          <p className="mt-3">La División Táctica MEIS Medioambiente tiene por misión prevenir, monitorear y responder a emergencias ambientales mediante protocolos tácticos, coordinación con autoridades locales y programas de educación comunitaria.</p>

          <div className="mt-6 grid md:grid-cols-3 gap-4">
            <div className="p-4 border rounded-lg">
              <h4 className="font-semibold">Prevención</h4>
              <p className="text-sm mt-2">Capacitaciones y vigilancia en puntos críticos.</p>
            </div>
            <div className="p-4 border rounded-lg">
              <h4 className="font-semibold">Respuesta</h4>
              <p className="text-sm mt-2">Equipos tácticos preparados 24/7 para intervenciones.</p>
            </div>
            <div className="p-4 border rounded-lg">
              <h4 className="font-semibold">Recuperación</h4>
              <p className="text-sm mt-2">Programas de restauración ambiental y seguimiento.</p>
            </div>
          </div>
        </section>

        {/* Proyectos */}
        <section id="proyectos" className="mt-8">
          <h3 className="text-2xl font-bold">Proyectos actuales</h3>
          <div className="mt-4 grid md:grid-cols-3 gap-4">
            <article className="bg-white p-4 rounded-lg shadow">
              <h4 className="font-semibold">Monitoreo de cuencas</h4>
              <p className="text-sm mt-2">Instalación de sensores y recorridos tácticos para detección temprana de contaminación.</p>
            </article>
            <article className="bg-white p-4 rounded-lg shadow">
              <h4 className="font-semibold">Limpieza comunitaria</h4>
              <p className="text-sm mt-2">Jornadas con la comunidad para recuperación de zonas verdes y riberas.</p>
            </article>
            <article className="bg-white p-4 rounded-lg shadow">
              <h4 className="font-semibold">Respuesta a derrames</h4>
              <p className="text-sm mt-2">Protocolos tácticos y kits de contención para fluidos peligrosos.</p>
            </article>
          </div>
        </section>

        {/* Report form + Map */}
        <section id="alertas" className="mt-10 grid lg:grid-cols-2 gap-6">
          <div className="bg-white p-6 rounded-lg shadow">
            <h3 className="text-xl font-bold mb-4">Reportar incidente</h3>
            <form onSubmit={sendAlert} className="space-y-3">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <input required name="nombre" value={form.nombre} onChange={handleChange} placeholder="Tu nombre" className="p-3 border rounded" />
                <input name="telefono" value={form.telefono} onChange={handleChange} placeholder="Teléfono / WhatsApp" className="p-3 border rounded" />
              </div>

              <input name="ubicacion" value={form.ubicacion} onChange={handleChange} placeholder="Ubicación (dirección o coordenadas)" className="p-3 border rounded w-full" />

              <select name="categoria" value={form.categoria} onChange={handleChange} className="p-3 border rounded w-full">
                <option>Incidente Ambiental</option>
                <option>Derrame de Hidrocarburos</option>
                <option>Contaminación de Agua</option>
                <option>Deforestación / Tala</option>
                <option>Otro</option>
              </select>

              <textarea required name="mensaje" value={form.mensaje} onChange={handleChange} placeholder="Describe lo sucedido" className="p-3 border rounded w-full h-28" />

              <div className="flex items-center gap-2">
                <button type="submit" className="px-4 py-2 rounded bg-emerald-600 text-white">Enviar reporte</button>
                <button type="button" onClick={() => { setForm({ nombre: '', telefono: '', ubicacion: '', mensaje: '', categoria: 'Incidente Ambiental' }) }} className="px-4 py-2 rounded border">Limpiar</button>
              </div>

              <p className="text-xs opacity-80">En caso de emergencia real llame a las autoridades locales además de reportar aquí.</p>
            </form>

            <div className="mt-6">
              <h4 className="font-semibold">Panel local de alertas</h4>
              <div className="mt-3 divide-y">
                {alerts.length===0 && <p className="text-sm opacity-80">No hay alertas registradas.</p>}
                {alerts.map(a => (
                  <div key={a.id} className="py-2 flex justify-between items-start">
                    <div>
                      <div className="text-sm font-medium">{a.categoria} — {new Date(a.fecha).toLocaleString()}</div>
                      <div className="text-xs opacity-80">{a.nombre} • {a.telefono} • {a.ubicacion}</div>
                      <div className="mt-1 text-sm">{a.mensaje}</div>
                      <div className="mt-1 text-xs">Estado: <strong>{a.estado}</strong></div>
                    </div>
                    <div className="flex flex-col gap-2 ml-4">
                      {a.estado !== 'Atendida' && <button onClick={() => markAttended(a.id)} className="px-3 py-1 rounded bg-emerald-600 text-white text-sm">Marcar atendida</button>}
                      <button onClick={() => removeAlert(a.id)} className="px-3 py-1 rounded border text-sm">Eliminar</button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className="bg-white p-6 rounded-lg shadow flex flex-col">
            <h3 className="text-xl font-bold mb-4">Mapa de monitoreo</h3>
            <div className="flex-1 min-h-[300px] rounded overflow-hidden shadow-inner">
              {/* Replace src with your Google Maps embed or Mapbox iframe */}
              <iframe title="mapa-meis" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d317716.6053053059!2d-74.2598663!3d4.624335!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8e3f99b6b7e3c8a5%3A0x3b8e1e7f6d8f9c4!2sBogot%C3%A1%2C%20Colombia!5e0!3m2!1ses!2sco!4v1690000000000" className="w-full h-full border-0" />
            </div>

            <div className="mt-4 text-sm opacity-80">Consejo: integra aquí tu sistema de geolocalización en tiempo real para mostrar alertas en el mapa con marcadores y rutas de respuesta.</div>
          </div>
        </section>

        {/* Contacto */}
        <section id="contacto" className="mt-10 bg-white p-6 rounded-lg shadow">
          <h3 className="text-2xl font-bold">Contacto</h3>
          <div className="mt-4 grid md:grid-cols-2 gap-6">
            <div>
              <p className="flex items-center gap-2"><MapPin size={16}/> Dirección: Oficina Central — Ciudad</p>
              <p className="flex items-center gap-2 mt-2"><Phone size={16}/> Tel: +57 300 000 0000</p>
              <p className="flex items-center gap-2 mt-2"><Mail size={16}/> Email: medioambiente@meis.org</p>

              <div className="mt-6">
                <h4 className="font-semibold">Redes</h4>
                <p className="text-sm opacity-80">Twitter / Facebook / Instagram — enlaces a añadir</p>
              </div>
            </div>

            <form className="space-y-3" onSubmit={(e)=>{e.preventDefault(); window.location.href = `mailto:medioambiente@meis.org?subject=Contacto%20MEIS&body=${encodeURIComponent('Mensaje de: '+(e.target.nombre?.value||'')+'\n\n'+(e.target.mensaje?.value||''))}`}}>
              <input name="nombre" placeholder="Nombre" className="p-3 border rounded w-full" />
              <input name="email" placeholder="Correo" className="p-3 border rounded w-full" />
              <textarea name="mensaje" placeholder="Tu mensaje" className="p-3 border rounded w-full h-28" />
              <button type="submit" className="px-4 py-2 rounded bg-emerald-600 text-white">Enviar</button>
            </form>
          </div>
        </section>

        {/* Footer */}
        <footer className="mt-12 text-center text-sm opacity-80">
          <p>© {new Date().getFullYear()} División Táctica MEIS — Medioambiente · Todos los derechos reservados.</p>
        </footer>
      </main>
    </div>
  );
}
