/* global React, SectionShell, Eyebrow, Icon */
/* Sección "Reflexión del día" (#reflexion).
   Enseña la ÚLTIMA newsletter que David ha enviado y un contador hasta la siguiente. Es lo
   único de la página que cambia a diario, así que da motivo para volver, y es la muestra
   gratis del pilar de mentalidad: por eso enlaza a la newsletter, que es donde se capta. */

const { useState, useEffect, useRef } = React;

const ES_LOCAL = ['localhost', '127.0.0.1'].indexOf(window.location.hostname) !== -1;

function dosCifras(n) { return String(n).padStart(2, '0'); }

// Devuelve { h, m, s } o null si el instante ya pasó.
function restante(objetivoMs, ahoraMs) {
  const ms = objetivoMs - ahoraMs;
  if (!objetivoMs || ms <= 0) return null;
  const total = Math.floor(ms / 1000);
  return { h: Math.floor(total / 3600), m: Math.floor((total % 3600) / 60), s: total % 60 };
}

function Contador({ objetivoIso }) {
  const [ahora, setAhora] = useState(Date.now());
  useEffect(() => {
    const t = setInterval(() => setAhora(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);

  const objetivoMs = objetivoIso ? new Date(objetivoIso).getTime() : 0;
  const r = restante(objetivoMs, ahora);

  // Sin instante al que apuntar (el endpoint no responde todavía) no se enseña contador:
  // un "Publicándose…" eterno promete algo que no va a pasar y confunde más que no poner nada.
  // "Publicándose…" queda para cuando SÍ había una hora y ya ha pasado.
  if (!objetivoIso) return null;

  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      flexWrap: 'wrap', marginTop: 22 }}>
      <Icon name="clock" size={17} color="var(--fg-3)" />
      <span style={{ fontFamily: 'var(--font-head)', fontWeight: 600, fontSize: 12.5,
        letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>
        {r ? 'Siguiente reflexión en' : 'Publicándose…'}
      </span>
      {r && (
        <span style={{ fontFamily: 'var(--font-head)', fontWeight: 800, fontSize: 19,
          letterSpacing: '.04em', color: 'var(--neon-cyan)', textShadow: 'var(--text-glow-cyan)',
          fontVariantNumeric: 'tabular-nums' }}>
          {dosCifras(r.h)}:{dosCifras(r.m)}:{dosCifras(r.s)}
        </span>
      )}
    </div>
  );
}

function Reflexion() {
  const [datos, setDatos] = useState(null);   // null = cargando
  const [abierta, setAbierta] = useState(false);
  const reintentado = useRef(false);
  // "Leer entera" solo tiene sentido si el texto NO cabe: una reflexión corta se lee de
  // una vez y el botón sobraba (parecía que faltaba texto cuando no faltaba nada).
  const cuerpoRef = useRef(null);
  const [recortada, setRecortada] = useState(false);

  useEffect(() => {
    let vivo = true;
    // En local no hay endpoint desplegado: cualquier respuesta que no sea una reflexión
    // buena cae en el ejemplo, pero SOLO en local. En producción, estado vacío.
    const respaldo = () => (ES_LOCAL ? window.CDT_REFLEXION_DEMO : { ok: false });
    fetch(window.CDT_REFLEXION_ENDPOINT, { method: 'GET' })
      .then((r) => r.json())
      .then((d) => { if (vivo) setDatos(d && d.ok ? d : respaldo()); })
      .catch(() => { if (vivo) setDatos(respaldo()); });
    return () => { vivo = false; };
  }, []);

  // Cuando el contador llega a cero, la nueva tarda un poco en aparecer: reintentamos UNA vez
  // al minuto, no cada segundo.
  useEffect(() => {
    if (!datos || !datos.siguiente_en || reintentado.current) return;
    const faltan = new Date(datos.siguiente_en).getTime() - Date.now();
    if (faltan > 0 && faltan < 86400000) {
      const t = setTimeout(() => { reintentado.current = true; location.reload(); }, faltan + 60000);
      return () => clearTimeout(t);
    }
  }, [datos]);

  // Se mide DESPUÉS de pintar el HTML, que es cuando se sabe el alto de verdad.
  useEffect(() => {
    const el = cuerpoRef.current;
    if (!el) { setRecortada(false); return; }
    setRecortada(el.scrollHeight > el.clientHeight + 4);
  }, [datos]);

  const cargando = datos === null;
  const r = datos && datos.reflexion ? datos.reflexion : null;

  return (
    <SectionShell id="reflexion">
      <div style={{ textAlign: 'center', maxWidth: 640, margin: '0 auto' }}>
        <Eyebrow color="var(--neon-magenta)" style={{ display: 'inline-block' }}>Reflexión del día</Eyebrow>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(28px,4vw,46px)',
          lineHeight: 1.06, textTransform: 'uppercase', color: 'var(--fg-1)', margin: '16px 0 0' }}>
          La reflexión<br /><span style={{ color: 'var(--neon-magenta)', textShadow: 'var(--text-glow-magenta)' }}>de hoy</span>
        </h2>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 'clamp(15px,1.4vw,17px)', lineHeight: 1.6,
          color: 'var(--fg-2)', margin: '18px 0 0' }}>
          Cada día, un mensaje para que pares y te cuestiones. El mismo que reciben por correo los que están dentro.
        </p>
      </div>

      <div style={{ maxWidth: 720, margin: 'clamp(30px,4vw,44px) auto 0', background: 'var(--surface-3)',
        border: '1px solid var(--hairline)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-card)',
        padding: 'clamp(26px,4vw,40px)' }}>

        {cargando ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[70, 100, 100, 85].map((w, i) => (
              <div key={i} style={{ height: i === 0 ? 26 : 14, width: w + '%', borderRadius: 'var(--r-sm)',
                background: 'var(--surface-2)' }} />
            ))}
          </div>
        ) : r ? (
          <React.Fragment>
            <h3 style={{ fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 'clamp(19px,2.4vw,25px)',
              lineHeight: 1.25, color: 'var(--fg-1)', margin: '0 0 16px' }}>{r.titulo}</h3>
            <div
              ref={cuerpoRef}
              style={{ position: 'relative', fontFamily: 'var(--font-body)', fontSize: 15.5, lineHeight: 1.7,
                color: 'var(--fg-2)', maxHeight: abierta ? 'none' : 320, overflow: 'hidden' }}
              dangerouslySetInnerHTML={{ __html: r.html }}
            />
            {!abierta && recortada && (
              <button type="button" onClick={() => setAbierta(true)}
                style={{ marginTop: 14, background: 'transparent', border: 'none', cursor: 'pointer', padding: 0,
                  fontFamily: 'var(--font-head)', fontWeight: 600, fontSize: 13, letterSpacing: '.06em',
                  textTransform: 'uppercase', color: 'var(--neon-cyan)' }}>
                Leer entera →
              </button>
            )}
          </React.Fragment>
        ) : (
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 16, lineHeight: 1.6, color: 'var(--fg-2)',
            margin: 0, textAlign: 'center' }}>
            La primera reflexión está en camino.
          </p>
        )}

        <Contador objetivoIso={datos && datos.siguiente_en} />

        <div style={{ textAlign: 'center', marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--hairline)' }}>
          <a href="#newsletter" style={{ fontFamily: 'var(--font-head)', fontWeight: 600, fontSize: 13.5,
            letterSpacing: '.04em', color: 'var(--fg-2)', textDecoration: 'underline' }}>
            Recíbela por correo →
          </a>
        </div>
      </div>
    </SectionShell>
  );
}

window.Reflexion = Reflexion;
