// notifications.jsx — live social-proof toaster

const NOTIF_NAMES = [
  'Sofía Hernández','Mateo Rodríguez','Valentina Pérez','Santiago López','Camila Torres',
  'Diego Ramírez','Lucía Morales','Joaquín Vargas','Isabella Castro','Tomás Herrera',
  'Renata Jiménez','Emiliano Cruz','Martina Reyes','Alejandro Soto','Antonella Silva',
  'Sebastián Mendoza','Regina Vega','Andrés Cabrera','Daniela Ríos','Nicolás Salazar',
  'Paula Aguilar','Joaquina Domínguez','Cristóbal Navarro','Helena Paredes','Bruno Ortega',
  'Gabriela Suárez','Iván Cárdenas','Mariana Escobar','Felipe Bustamante','Florencia Aguirre',
  'Luciano Quintero','Constanza Maldonado','Rodrigo Espinoza','Ximena Lagos','Maximiliano Pizarro',
  'Carolina Mejía','Pablo Villalba','Agustina Pacheco','Ricardo Carmona','Macarena Olivares',
  'Hernán Galindo','Trinidad Bolaños','Esteban Arteaga','Renata Quispe','Vicente Acuña',
  'Marina Tapia','Ignacio Bermúdez','Catalina Andrade','Raúl Fuentes','Belén Cisneros',
  'Tobías Saavedra','Julieta Cordero','Cristián Beltrán','Amparo Solís','Bautista Páez',
];

const COUNTRIES = [
  { code: 'MX', name: 'México', states: [
    'Ciudad de México','Jalisco','Nuevo León','Puebla','Guanajuato',
    'Querétaro','Yucatán','Chihuahua','Sonora','Baja California',
    'Michoacán','Veracruz'
  ] },
  { code: 'CO', name: 'Colombia', states: [
    'Bogotá','Antioquia','Valle del Cauca','Atlántico','Santander',
    'Boyacá','Cundinamarca','Risaralda','Tolima','Caldas'
  ] },
  { code: 'PE', name: 'Perú', states: [
    'Lima','Arequipa','Cusco','La Libertad','Piura',
    'Lambayeque','Junín','Ica','Loreto'
  ] },
  { code: 'AR', name: 'Argentina', states: [
    'Buenos Aires','CABA','Córdoba','Santa Fe','Mendoza',
    'Tucumán','Salta','Entre Ríos','Neuquén'
  ] },
  { code: 'EC', name: 'Ecuador', states: [
    'Pichincha','Guayas','Azuay','Manabí','Tungurahua',
    'Loja','El Oro','Imbabura'
  ] },
  // US states stay as 2-letter abbreviations per requirement
  { code: 'US', name: 'EE.UU.', states: ['FL','TX','CA','NY','NJ','IL','GA','AZ','NV','MA'], abbr: true },
];

// Fallback abbreviations for the rare overflow case
const STATE_ABBR = {
  'Ciudad de México': 'CDMX',
  'Valle del Cauca': 'V. del Cauca',
  'Buenos Aires': 'Bs. As.',
  'La Libertad': 'La Libertad',
  'Entre Ríos': 'Entre Ríos',
};

const MESSAGES = [
  'se inscribió en el workshop',
  'reservó su plaza',
  'acaba de inscribirse',
  'aseguró su lugar',
  'se unió al lote 1',
];

const AVATAR_GRADIENTS = [
  ['#7C5CFF','#22D3EE'],
  ['#FF6B4A','#F5C842'],
  ['#C7F752','#22D3EE'],
  ['#FF6B9D','#7C5CFF'],
  ['#22D3EE','#4ADE80'],
  ['#F5C842','#FF6B4A'],
  ['#A78BFA','#EC4899'],
  ['#34D399','#22D3EE'],
];

function pick(arr, exclude) {
  let v;
  let tries = 0;
  do {
    v = arr[Math.floor(Math.random() * arr.length)];
    tries++;
  } while (exclude && exclude.has(v) && tries < 30);
  return v;
}

function initials(name) {
  return name.split(' ').filter(Boolean).slice(0,2).map(p => p[0]).join('').toUpperCase();
}

function formatLocation(country, state) {
  const full = `${country}, ${state}`;
  // Notification width fits ~26-28 chars before wrapping awkwardly.
  // Only fall back to abbr if the full label is too long AND we have one.
  if (full.length <= 28) return full;
  const abbr = STATE_ABBR[state];
  if (abbr) return `${country}, ${abbr}`;
  return full; // let CSS handle wrap/ellipsis
}

function buildNotif(usedNames) {
  const name = pick(NOTIF_NAMES, usedNames);
  usedNames.add(name);
  if (usedNames.size > 30) {
    const first = usedNames.values().next().value;
    usedNames.delete(first);
  }
  const country = COUNTRIES[Math.floor(Math.random() * COUNTRIES.length)];
  const state = country.states[Math.floor(Math.random() * country.states.length)];
  const message = MESSAGES[Math.floor(Math.random() * MESSAGES.length)];
  const grad = AVATAR_GRADIENTS[Math.floor(Math.random() * AVATAR_GRADIENTS.length)];
  const minsAgo = Math.floor(Math.random() * 14) + 1;
  return {
    id: Date.now() + Math.random(),
    name, state, country: country.name,
    message, grad,
    timeLabel: `hace ${minsAgo} min`,
  };
}

function NotifStack() {
  const [items, setItems] = React.useState([]);
  const [leaving, setLeaving] = React.useState(new Set());
  const usedRef = React.useRef(new Set());

  React.useEffect(() => {
    let timer;
    const schedule = (ms) => {
      timer = setTimeout(() => {
        const n = buildNotif(usedRef.current);
        setItems(prev => [...prev.slice(-2), n]);

        // schedule auto-dismiss for this one
        const dismissAfter = 6500;
        setTimeout(() => {
          setLeaving(s => new Set(s).add(n.id));
          setTimeout(() => {
            setItems(prev => prev.filter(p => p.id !== n.id));
            setLeaving(s => { const c = new Set(s); c.delete(n.id); return c; });
          }, 360);
        }, dismissAfter);

        // next notif in 9-13s
        const next = 9000 + Math.random() * 4000;
        schedule(next);
      }, ms);
    };
    // first notif after 6s
    schedule(6000);
    return () => clearTimeout(timer);
  }, []);

  return (
    <div className="notif-stack" aria-live="polite" aria-label="Inscripciones recientes">
      {items.map(n => (
        <div
          key={n.id}
          className={`notif ${leaving.has(n.id) ? 'notif--leaving' : ''}`}
        >
          <div
            className="notif__avatar"
            style={{ background: `linear-gradient(135deg, ${n.grad[0]}, ${n.grad[1]})` }}
          >
            {initials(n.name)}
          </div>
          <div className="notif__body">
            <div className="notif__head">
              <span className="notif__name">{n.name}</span>
              <span className="notif__time">{n.timeLabel}</span>
            </div>
            <div className="notif__msg">
              <span className="accent">✓ Se inscribió</span> en el workshop
            </div>
            <div className="notif__loc">{formatLocation(n.country, n.state)}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

window.NotifStack = NotifStack;
