// ScreenMain.jsx — home / dashboard
// WX_CODES and useWeather are now defined in Data.jsx and exported via window.

// ── Screen ───────────────────────────────────────────────────────────
function ScreenMain({ go, t, authed }) {
  const [tick, setTick] = React.useState(0);
  const [isFullscreen, setIsFullscreen] = React.useState(false);
  React.useEffect(() => {
    const i = setInterval(() => setTick(x => x + 1), 90);
    return () => clearInterval(i);
  }, []);
  React.useEffect(() => {
    const fn = () => setIsFullscreen(!!document.fullscreenElement);
    document.addEventListener('fullscreenchange', fn);
    return () => document.removeEventListener('fullscreenchange', fn);
  }, []);
  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      (document.documentElement.requestFullscreen || document.documentElement.webkitRequestFullscreen || (() => {})).call(document.documentElement);
    } else {
      (document.exitFullscreen || document.webkitExitFullscreen || (() => {})).call(document);
    }
  };
  const lineStatus = useLiveStatus();
  const wx = useWeather();

  // Exclude lines that are simply out-of-service-hours — those aren't "alerts"
  const alerts = Object.entries(lineStatus).filter(([id, s]) =>
    s.state !== 'normal' && getServiceState(id).state !== 'closed'
  );
  const mainLines = LINES.filter(l => ['A','B','C','D','E','H'].includes(l.id));
  const extraLines = LINES.filter(l => ['U','P'].includes(l.id));

  // ¿Toda la red cerrada? → próximo inicio
  const allClosedInfo = getAllClosedInfo();

  // Anuncios desestimables (Emova X). Persistido en localStorage.
  const [dismissed, setDismissed] = React.useState(() => loadDismissed());
  const activeAnns = React.useMemo(() => {
    const list = getActiveAnnouncements(dismissed);

    // Agregar anuncios del CMS (guardados en window.CMS_ANNOUNCEMENTS)
    if (window.CMS_ANNOUNCEMENTS && Array.isArray(window.CMS_ANNOUNCEMENTS)) {
      window.CMS_ANNOUNCEMENTS.forEach(a => {
        if (!dismissed.has(a.id)) list.push(a);
      });
    }

    // Inyección automática: si el clima actual sugiere lluvia/tormenta y el
    // anuncio sintético no fue descartado, lo agregamos al tope.
    const wxId = 'auto-weather-' + (wx?.code ?? '?');
    if (wx && wx.code >= 51 && wx.code <= 99 && !dismissed.has(wxId)) {
      list.unshift({
        id: wxId,
        kind: 'weather',
        lineId: null,
        text: `${wx.icon} ${wx.desc} en CABA. Pueden producirse demoras y filtraciones en estaciones a cielo abierto.`,
        images: [],
        url: 'https://www.smn.gob.ar/',
        source: SOURCES.smn,
        createdAt: new Date().toISOString(),
      });
    }
    return list;
  }, [dismissed, tick, wx]);
  const dismissAnn = (id) => {
    const next = new Set(dismissed); next.add(id); saveDismissed(next); setDismissed(next);
  };

  // Status events — loaded once on mount, independent of push prefs
  const [statusEvents, setStatusEvents] = React.useState([]);
  React.useEffect(() => {
    loadStatusEvents(5).then(evs => setStatusEvents(evs || []));
  }, []);

  return (
    <div className="scroll-area">
      <AppBar
        large
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'nowrap' }}>
            {/* weather icon + temp */}
            {wx ? (
              <>
                <span style={{ fontSize: 32, lineHeight: 1, flexShrink: 0 }}>{wx.icon}</span>
                <div style={{ flexShrink: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                    <span style={{ fontSize: 28, fontWeight: 800, fontFamily: 'var(--font-display)', letterSpacing: '-.02em', lineHeight: 1 }}>{wx.temp}°</span>
                    <span style={{ fontSize: 13, color: 'var(--text-muted)', fontWeight: 600 }}>ST {wx.feels}°</span>
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-muted)', fontWeight: 600, marginTop: 1 }}>{wx.desc}</div>
                </div>
              </>
            ) : (
              <span style={{ color: 'var(--text-muted)', fontSize: 22, fontWeight: 700 }}>Buenos Aires</span>
            )}
            {/* live update time — same horizontal row, pushed right */}
            <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--text-muted)', fontFamily: 'var(--font-display)', fontWeight: 600, whiteSpace: 'nowrap', flexShrink: 0 }}>
              <span className="live-dot" />
              {new Date().toLocaleTimeString('es-AR',{hour:'2-digit',minute:'2-digit'})}
            </div>
          </div>
        }
        subtitle={null}
        left={<Logo size={36} />}
        right={
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'center' }}>
            <button onClick={toggleFullscreen} title={isFullscreen ? 'Salir de pantalla completa' : 'Pantalla completa'}
              style={{ width: 38, height: 38, borderRadius: 19, background: 'var(--ink-100)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <I name={isFullscreen ? 'minimize' : 'maximize'} size={16} />
            </button>
            <button onClick={() => go('settings')}
              style={{ width: 38, height: 38, borderRadius: 19, background: 'var(--ink-100)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <I name="bell" size={18} />
            </button>
          </div>
        }
      />

      {/* Summary banner */}
      <div style={{ padding: '4px 20px 14px' }}>
        {allClosedInfo.allClosed ? (
          <div style={{ padding: 14, borderRadius: 14, background: 'var(--ink-100)', color: 'var(--text)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: 16, background: 'var(--ink-300)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <I name="moon" size={18} style={{ stroke: 'white' }} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontFamily: 'var(--font-display)', fontWeight: 700 }}>Servicio finalizado en toda la red</div>
              <div style={{ fontSize: 11, marginTop: 2, color: 'var(--text-muted)' }}>Inicio del servicio nuevamente {allClosedInfo.opensDay} a las {allClosedInfo.opensAt}</div>
            </div>
          </div>
        ) : alerts.length === 0 && CLOSED_TODAY.length === 0 ? (
          <div style={{ padding: 14, borderRadius: 14, background: 'oklch(0.94 0.04 155)', color: 'oklch(0.3 0.08 155)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: 16, background: 'var(--ok)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <I name="check" size={18} style={{ stroke: 'white' }} />
            </div>
            <div style={{ fontSize: 13, fontFamily: 'var(--font-display)', fontWeight: 700 }}>{t('allNormal')}</div>
          </div>
        ) : alerts.length === 0 && CLOSED_TODAY.length > 0 ? (
          <div style={{ padding: 14, borderRadius: 14, background: 'oklch(0.96 0.05 75)', border: '1px solid oklch(0.85 0.12 75)', color: 'oklch(0.35 0.15 75)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: 16, background: 'var(--warn)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <I name="warning" size={18} style={{ stroke: '#0B1220' }} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontFamily: 'var(--font-display)', fontWeight: 700 }}>{CLOSED_TODAY.length} estación{CLOSED_TODAY.length > 1 ? 'es' : ''} cerrada{CLOSED_TODAY.length > 1 ? 's' : ''}</div>
              <div style={{ fontSize: 11, marginTop: 2 }}>{CLOSED_TODAY.join(' · ')}</div>
            </div>
          </div>
        ) : (
          <div style={{ padding: 14, borderRadius: 14, background: 'oklch(0.96 0.05 75)', border: '1px solid oklch(0.85 0.12 75)', color: 'oklch(0.35 0.15 75)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: 16, background: 'var(--warn)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <I name="warning" size={18} style={{ stroke: '#0B1220' }} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontFamily: 'var(--font-display)', fontWeight: 700 }}>{alerts.length} {t('linesWithIssues')}</div>
              <div style={{ fontSize: 11, marginTop: 2 }}>{alerts.map(([id]) => id).join(' · ')}</div>
            </div>
          </div>
        )}
      </div>

      {/* Anuncios trascendentales (Emova X) — desestimables */}
      {activeAnns.length > 0 && (
        <div style={{ padding: '0 20px 14px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {activeAnns.map(a => <AnnouncementCard key={a.id} ann={a} onDismiss={() => dismissAnn(a.id)} />)}
        </div>
      )}

      {/* Main line cards (A-H) — 2 cols mobile, 3 cols ≥540px */}
      <div style={{ padding: '0 20px', display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(140px,1fr))', gap: 12, marginBottom: 12 }}>
        {mainLines.map(line => {
          const st = lineStatus[line.id];
          const isY = line.id === 'H';
          const txt = isY ? '#0B1220' : '#fff';
          const sub = isY ? 'rgba(11,18,32,.7)' : 'rgba(255,255,255,.85)';
          const hasClosed = line.stations.some(s => CLOSED_TODAY.includes(s));
          const svc = getServiceState(line.id);
          const closed = svc.state === 'closed';
          const closingSoon = svc.state === 'closing-soon';
          const minsLeft = closingSoon ? Math.max(1, Math.round(svc.minsUntilClose)) : null;
          return (
            <button key={line.id} className={'grad-'+line.id.toLowerCase()} onClick={() => go('lineDetail',{line:line.id})}
              style={{ borderRadius: 18, padding: 14, color: txt, textAlign: 'left', minHeight: 134, display: 'flex', flexDirection: 'column', border: 'none', boxShadow: 'var(--shadow-sm)', position: 'relative', overflow: 'hidden' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div style={{ width: 40, height: 40, borderRadius: 12, background: 'rgba(255,255,255,.22)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 22, color: txt }}>{line.id}</div>
                {/* Single status dot: hasClosed overrides to orange, else follows service state */}
                <div style={{ width: 8, height: 8, borderRadius: 4, marginTop: 6,
                  background: closed    ? 'rgba(255,255,255,.45)'
                            : hasClosed ? '#FF9F43'
                            : st.state === 'normal' ? '#86E8C9'
                            : st.state === 'delay'  ? '#FFE187'
                            : '#FFB5B5'
                }} />
              </div>
              <div style={{ flex: 1 }} />
              <div style={{ fontSize: closed ? 14 : 18, fontFamily: 'var(--font-display)', fontWeight: 800, lineHeight: 1 }}>
                {closed ? `1° tren ${svc.opensDay} ${svc.opensAt}` : st.freq}
              </div>
              <div className={closingSoon ? 'blink' : ''} style={{ fontSize: 10, color: sub, marginTop: 2, textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 700 }}>
                {closed                  ? 'Fin del servicio'
                 : closingSoon           ? `⚠ Último tren en ${minsLeft} min`
                 : st.state === 'normal' ? t('normalService')
                 : st.state === 'delay'  ? t('delays')
                 : t('alert')}
              </div>
            </button>
          );
        })}
      </div>

      {/* Secondary lines: Urquiza + Premetro — wrap to column on narrow screens */}
      <div style={{ padding: '0 20px 14px', display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(160px,1fr))', gap: 10 }}>
        {extraLines.map(line => {
          const st = lineStatus[line.id];
          const svc = getServiceState(line.id);
          const closed = svc.state === 'closed';
          const closingSoon = svc.state === 'closing-soon';
          const minsLeft = closingSoon ? Math.max(1, Math.round(svc.minsUntilClose)) : null;
          return (
            <button key={line.id} onClick={() => go('lineDetail',{line:line.id})}
              style={{ padding: '10px 14px', borderRadius: 14, background: `var(--linea-${line.id.toLowerCase()}-2,var(--linea-p-2))`, color: line.id === 'P' ? '#0B1220' : 'white', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 10, border: 'none', boxShadow: 'var(--shadow-sm)', minWidth: 0 }}>
              <div style={{ width: 34, height: 34, borderRadius: 10, background: 'rgba(255,255,255,.22)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 16, flexShrink: 0 }}>{line.id}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 12, opacity: .85, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{line.name}</div>
                <div style={{ fontSize: closed ? 12 : 16, fontFamily: 'var(--font-display)', fontWeight: 800, lineHeight: 1.1, marginTop: 2 }}>
                  {closed ? `1° tren ${svc.opensDay} ${svc.opensAt}` : st.freq}
                </div>
              </div>
              <div className={closingSoon ? 'blink' : ''} style={{ textAlign: 'right', fontSize: 10, opacity: .85, flexShrink: 0 }}>
                <div style={{ width: 7, height: 7, borderRadius: 4, background: closed ? 'rgba(255,255,255,.45)' : closingSoon ? '#FFE187' : st.state === 'normal' ? '#86E8C9' : st.state === 'delay' ? '#FFE187' : '#FFB5B5', marginLeft: 'auto', marginBottom: 4 }} />
                {closed ? 'cerrado' : closingSoon ? `⚠ último tren ${minsLeft}m` : st.state === 'normal' ? t('normalService') : t('delays')}
              </div>
            </button>
          );
        })}
      </div>

      {/* Mini map preview — Leaflet real map, non-interactive */}
      <div style={{ padding: '0 20px 16px' }}>
        <div className="card" style={{ padding: 16, position: 'relative', overflow: 'hidden' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 15 }}> {/* {t('liveTrains')} */} </div>
            <button onClick={() => go('map')} style={{ fontSize: 12, color: 'var(--info)', fontFamily: 'var(--font-display)', fontWeight: 700, display: 'flex', alignItems: 'center', gap: 4 }}>{t('openMap')} <I name="arrowRight" size={14} /></button>
          </div>
          {/* Click overlay routes to full map */}
          <div style={{ height: 190, borderRadius: 10, overflow: 'hidden', position: 'relative' }}>
            <LeafletMap mini showTrains={false} showEntrances={false} />
            <div
              onClick={() => go('map')}
              style={{ position: 'absolute', inset: 0, zIndex: 500, cursor: 'pointer' }}
            />
          </div>
        </div>
      </div>

      {/* Quick actions */}
      <div style={{ padding: '0 20px 16px' }}>
        <button onClick={() => go('incidentReport')} className="card" style={{ padding: 14, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12, width: '100%' }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'oklch(0.96 0.08 25)', color: 'oklch(0.45 0.15 25)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <I name="warning" size={18} />
          </div>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13 }}>{t('reportIncident')}</div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>vandalismo · accesibilidad · seguridad</div>
          </div>
        </button>
      </div>

      {/* News teaser — últimos 5 días de cambios de estado (infosubte) */}
      <div style={{ padding: '0 20px 20px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <h2 style={{ fontSize: 16 }}>{t('news')}</h2>
          <button onClick={() => go('news')} style={{ fontSize: 12, color: 'var(--info)', fontFamily: 'var(--font-display)', fontWeight: 700 }}>ver todas →</button>
        </div>
        {statusEvents.length === 0 ? (
          <div style={{ fontSize: 13, color: 'var(--text-dim)', padding: '8px 0' }}>Sin novedades en los últimos 5 días.</div>
        ) : (
          statusEvents.slice(0, 5).map((ev, i) => (
            <StatusEventCard key={i} event={ev} />
          ))
        )}
      </div>
    </div>
  );
}

// ── StatusEventCard ──────────────────────────────────────────────────
// Muestra un evento de cambio de estado del infosubte (origen: ops.infosubte).
function StatusEventCard({ event: ev }) {
  const isAlert = !!ev.isCurrent;
  return (
    <div className="card" style={{ padding: 12, marginBottom: 8, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <div style={{ width: 32, height: 32, borderRadius: 16, background: 'var(--ink-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <LineChip id={ev.lineId} size="sm" />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3, flexWrap: 'wrap' }}>
          {isAlert && (
            <span style={{ fontSize: 10, fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.05em', color: 'oklch(0.45 0.18 25)', background: 'oklch(0.90 0.08 25)', borderRadius: 4, padding: '1px 5px' }}>En curso</span>
          )}
          <span style={{ fontSize: 10, color: 'var(--text-dim)', marginLeft: 'auto' }}>
            {timeAgoLabel(ev.startedAt)}
            {ev.endedAt && !ev.isCurrent && ` · duró ${timeAgoLabel(ev.startedAt).replace('hace ','')}`}
          </span>
        </div>
        <div style={{ fontSize: 13, fontFamily: 'var(--font-display)', fontWeight: 600, lineHeight: 1.4 }}>{ev.text}</div>
        {ev.endedAt && !ev.isCurrent && (
          <div style={{ fontSize: 11, color: 'var(--ok)', fontFamily: 'var(--font-display)', fontWeight: 700, marginTop: 3, display: 'flex', alignItems: 'center', gap: 4 }}>
            <I name="check" size={10} style={{ stroke: 'var(--ok)' }} />
            Resuelto {timeAgoLabel(ev.endedAt)}
          </div>
        )}
      </div>
    </div>
  );
}

// ── AnnouncementCard ─────────────────────────────────────────────────
// Tarjeta destacada para anuncios trascendentales (Emova X). Muestra texto
// + imágenes + link a la fuente. Se cierra con la X y se persiste en
// localStorage; reaparece en "Novedades" abajo.
function AnnouncementCard({ ann, onDismiss }) {
  const meta = ANNOUNCEMENT_KIND[ann.kind] || ANNOUNCEMENT_KIND.advisory;
  const tone = meta.tone;
  const bg   = tone === 'error' ? 'oklch(0.96 0.06 25)'
             : tone === 'warn'  ? 'oklch(0.96 0.05 75)'
             : tone === 'info'  ? 'oklch(0.96 0.04 240)'
             :                    'oklch(0.94 0.04 155)';
  const bd   = tone === 'error' ? 'oklch(0.78 0.18 25)'
             : tone === 'warn'  ? 'oklch(0.85 0.12 75)'
             : tone === 'info'  ? 'oklch(0.82 0.10 240)'
             :                    'oklch(0.82 0.10 155)';
  const fg   = tone === 'error' ? 'oklch(0.40 0.18 25)'
             : tone === 'warn'  ? 'oklch(0.35 0.15 75)'
             : tone === 'info'  ? 'oklch(0.35 0.14 240)'
             :                    'oklch(0.30 0.10 155)';
  return (
    <div style={{ padding: 12, borderRadius: 14, background: bg, border: `1px solid ${bd}`, color: fg, display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 26, height: 26, borderRadius: 13, background: 'rgba(0,0,0,.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <I name={meta.icon} size={14} />
        </div>
        <div style={{ fontSize: 11, fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.05em' }}>{meta.label}</div>
        {ann.lineId && <LineChip id={ann.lineId} size="sm" />}
        <div style={{ flex: 1 }} />
        {ann.source && (
          <span style={{ fontSize: 10, opacity: .7, fontWeight: 700 }}>
            {ann.source.label}{ann.source.handle ? ` · ${ann.source.handle}` : ''}
          </span>
        )}
        <span style={{ fontSize: 10, opacity: .6 }}>· {timeAgoLabel(ann.createdAt)}</span>
        <button onClick={onDismiss} title="Cerrar" style={{ width: 24, height: 24, borderRadius: 12, background: 'rgba(0,0,0,.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <I name="x" size={12} />
        </button>
      </div>
      <div style={{ fontSize: 13, lineHeight: 1.4 }}>{ann.text}</div>
      {ann.images && ann.images.length > 0 && (
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto' }}>
          {ann.images.map((src, i) => (
            <img key={i} src={src} alt="" style={{ height: 100, borderRadius: 8, flexShrink: 0 }} />
          ))}
        </div>
      )}
      {ann.url && (
        <a href={ann.url} target="_blank" rel="noopener noreferrer"
           style={{ fontSize: 11, fontWeight: 700, color: fg, textDecoration: 'underline', display: 'inline-flex', alignItems: 'center', gap: 4, alignSelf: 'flex-start' }}>
          {(ann.source && ann.source.linkLabel) || 'Ver fuente'} <I name="arrowRight" size={12} />
        </a>
      )}
    </div>
  );
}

Object.assign(window, { ScreenMain, AnnouncementCard });
