// src/screen-discovery.jsx — Discovery Loop: animated data-journey explainer.
// 4-beat self-playing animation: póliza en equipo → valores morfan → solo sale la
// forma → Piixi aprende el formato.
// Mismo nombre de componente (DiscoveryLoopScreen) y ruta /discovery sin cambios.

// ─── Shared sub-components ────────────────────────────────────────────────────

function DLaptopFrame({ children, compact }) {
  const pad = compact ? 8 : 12;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      {/* Screen bezel */}
      <div style={{
        background: 'var(--ax-bg)',
        border: '2px solid var(--ax-border-strong)',
        borderRadius: compact ? '6px 6px 0 0' : '8px 8px 0 0',
        padding: pad,
        position: 'relative',
      }}>
        {/* Camera dot */}
        <div style={{
          position: 'absolute', top: 5, left: '50%',
          transform: 'translateX(-50%)',
          width: 4, height: 4, borderRadius: '50%',
          background: 'var(--ax-bg-3)',
          border: '1px solid var(--ax-border-strong)',
        }}/>
        <div style={{ marginTop: 6 }}>{children}</div>
      </div>
      {/* Base */}
      <div style={{
        width: '115%', height: compact ? 6 : 8,
        background: 'var(--ax-bg-3)',
        border: '1px solid var(--ax-border-strong)',
        borderTop: 'none',
        borderRadius: '0 0 5px 5px',
      }}/>
      <div style={{
        width: '72%', height: 3,
        background: 'var(--ax-bg-4)',
        borderRadius: '0 0 3px 3px',
      }}/>
    </div>
  );
}

// Full-size policy card (beats 1 & 2)
function DPolicyCardFull({ nombre, rfc, fnac, tel, poliza, struct, pColor, sColor }) {
  const pc = pColor || 'var(--ax-warm)';
  const sc = sColor || 'var(--ax-fg-faint)';
  return (
    <div style={{
      background: 'var(--ax-bg-3)',
      border: '1px solid var(--ax-border-strong)',
      borderRadius: 8, padding: '12px 14px', width: 244,
      fontFamily: 'var(--font-mono)', fontSize: 10,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 5,
        marginBottom: 9, paddingBottom: 7,
        borderBottom: '1px solid var(--ax-border)',
      }}>
        <AxIcon name="pdf" size={12} style={{ color: 'var(--ax-fg-muted)' }}/>
        <span style={{ fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ax-fg-muted)' }}>Póliza</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 9 }}>
        {[
          ['Nombre',    nombre],
          ['RFC',       rfc],
          ['F. Nac',    fnac],
          ['Teléfono',  tel],
          ['Nº póliza', poliza],
        ].map(([label, val]) => (
          <div key={label} style={{ display: 'flex', gap: 4, alignItems: 'baseline' }}>
            <span style={{ color: 'var(--ax-fg-faint)', minWidth: 52, flexShrink: 0 }}>{label}:</span>
            <span style={{ color: pc, transition: 'color 400ms' }}>{val}</span>
          </div>
        ))}
      </div>
      <div style={{ height: 1, background: 'var(--ax-border)', marginBottom: 7 }}/>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 3, color: sc, fontSize: 9, transition: 'color 400ms' }}>
        <div>{struct.producto}</div>
        <div>Prima: {struct.prima}</div>
        <div>Vigencia: {struct.vigencia}</div>
      </div>
    </div>
  );
}

// Compact card (beat 3 — left device + right flying copy)
function DPolicyCardSmall({ nombre, rfc, fnac, struct, masked, dimmed }) {
  return (
    <div style={{
      background: 'var(--ax-bg-3)',
      border: '1px solid ' + (masked ? 'var(--ax-accent-line)' : 'var(--ax-border)'),
      borderRadius: 7, padding: '9px 11px', width: 182,
      fontFamily: 'var(--font-mono)', fontSize: 9,
      opacity: dimmed ? 0.5 : 1,
      transition: 'border-color 400ms, opacity 400ms',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 4,
        marginBottom: 7, paddingBottom: 5,
        borderBottom: '1px solid var(--ax-border)',
      }}>
        <AxIcon name="pdf" size={10} style={{ color: masked ? 'var(--ax-accent)' : 'var(--ax-fg-faint)' }}/>
        <span style={{
          fontSize: 8, letterSpacing: '0.1em', textTransform: 'uppercase',
          color: masked ? 'var(--ax-accent)' : 'var(--ax-fg-faint)',
        }}>
          {masked ? 'Enmascarada' : 'Original'}
        </span>
      </div>
      <div style={{
        display: 'flex', flexDirection: 'column', gap: 3, marginBottom: 6,
        color: masked ? 'var(--ax-fg)' : 'var(--ax-fg-faint)',
      }}>
        {[['Nombre', nombre], ['RFC', rfc], ['F. Nac', fnac]].map(([l, v]) => (
          <div key={l} style={{ display: 'flex', gap: 3 }}>
            <span style={{ color: 'var(--ax-fg-faint)', minWidth: 40, flexShrink: 0 }}>{l}:</span>
            <span>{v}</span>
          </div>
        ))}
      </div>
      <div style={{ height: 1, background: 'var(--ax-border)', marginBottom: 5 }}/>
      <div style={{ color: 'var(--ax-fg-muted)', fontSize: 8, lineHeight: 1.4 }}>
        <div>{struct.producto}</div>
        <div>Prima: {struct.prima}</div>
      </div>
    </div>
  );
}

// ─── Beat 1: póliza en tu equipo ─────────────────────────────────────────────
function DLBeat1({ real, struct }) {
  return (
    <div className="ax-fade-in" style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '36px 24px 28px',
    }}>
      <DLaptopFrame>
        <DPolicyCardFull
          nombre={real.nombre} rfc={real.rfc} fnac={real.fnac}
          tel={real.tel} poliza={real.poliza} struct={struct}
          pColor="var(--ax-warm)"
          sColor="var(--ax-fg-faint)"
        />
      </DLaptopFrame>
    </div>
  );
}

// ─── Beat 2: morph — valores cambian, forma se conserva ──────────────────────
function DLBeat2({ real, fake, struct }) {
  const [vals, setVals] = useState({
    nombre: real.nombre, rfc: real.rfc, fnac: real.fnac, tel: real.tel, poliza: real.poliza,
  });
  const [done, setDone] = useState(false);
  const [structPulse, setStructPulse] = useState(false);

  useEffect(() => {
    const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const SEPS = { '-': 1, '/': 1, '.': 1, ' ': 1, '·': 1 };

    const morph = (fakeV, progress) => {
      const revealed = Math.floor(progress * fakeV.length);
      return fakeV.split('').map((ch, i) => {
        if (i < revealed) return fakeV[i];
        if (SEPS[fakeV[i]]) return fakeV[i];
        return CHARS[Math.floor(Math.random() * CHARS.length)];
      }).join('');
    };

    let frame = 0;
    const TOTAL = 14; // 1.4 s at 100 ms
    let pulseTimer = null;

    const tick = setInterval(() => {
      frame++;
      const p = Math.min(frame / TOTAL, 1);
      setVals({
        nombre:  morph(fake.nombre,  p),
        rfc:     morph(fake.rfc,     p),
        fnac:    morph(fake.fnac,    p),
        tel:     morph(fake.tel,     p),
        poliza:  morph(fake.poliza,  p),
      });
      if (frame >= TOTAL) {
        clearInterval(tick);
        setDone(true);
        setStructPulse(true);
        pulseTimer = setTimeout(() => setStructPulse(false), 1200);
      }
    }, 100);

    return () => {
      clearInterval(tick);
      if (pulseTimer) clearTimeout(pulseTimer);
    };
  }, []);

  return (
    <div className="ax-fade-in" style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '36px 24px 28px',
    }}>
      <DLaptopFrame>
        <div style={{
          background: 'var(--ax-bg-3)',
          border: '1px solid var(--ax-border-strong)',
          borderRadius: 8, padding: '12px 14px', width: 244,
          fontFamily: 'var(--font-mono)', fontSize: 10,
        }}>
          {/* Header */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 5,
            marginBottom: 9, paddingBottom: 7,
            borderBottom: '1px solid var(--ax-border)',
          }}>
            <AxIcon name="pdf" size={12} style={{ color: 'var(--ax-fg-muted)' }}/>
            <span style={{ fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ax-fg-muted)' }}>Póliza</span>
          </div>

          {/* Personal fields — rolling */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 9 }}>
            {[
              ['Nombre',    vals.nombre],
              ['RFC',       vals.rfc],
              ['F. Nac',    vals.fnac],
              ['Teléfono',  vals.tel],
              ['Nº póliza', vals.poliza],
            ].map(([label, val]) => (
              <div key={label} style={{ display: 'flex', gap: 4, alignItems: 'baseline' }}>
                <span style={{ color: 'var(--ax-fg-faint)', minWidth: 52, flexShrink: 0 }}>{label}:</span>
                <span style={{
                  color: done ? 'var(--ax-fg-strong)' : 'var(--ax-warm)',
                  transition: 'color 500ms',
                  fontFamily: 'var(--font-mono)',
                }}>
                  {val}
                </span>
              </div>
            ))}
          </div>

          {/* Divider — pulses green */}
          <div style={{
            height: 1,
            background: structPulse ? 'var(--ax-accent)' : 'var(--ax-border)',
            transition: 'background 300ms',
            marginBottom: 7,
          }}/>

          {/* Structural fields — pulse green momentarily */}
          <div style={{
            display: 'flex', flexDirection: 'column', gap: 3, fontSize: 9,
            color: structPulse ? 'var(--ax-accent)' : 'var(--ax-fg-faint)',
            transition: 'color 400ms',
          }}>
            {structPulse && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 3, marginBottom: 3 }}>
                <AxIcon name="check" size={9} style={{ color: 'var(--ax-accent)' }}/>
                <span style={{ fontSize: 8, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ax-accent)' }}>sin cambios</span>
              </div>
            )}
            <div>{struct.producto}</div>
            <div>Prima: {struct.prima}</div>
            <div>Vigencia: {struct.vigencia}</div>
          </div>
        </div>
      </DLaptopFrame>
    </div>
  );
}

// ─── Beat 3: split — original locked, masked copy flies to cloud ──────────────
function DLBeat3({ real, fake, struct }) {
  const [risen, setRisen] = useState(false);
  const [landed, setLanded] = useState(false);

  useEffect(() => {
    const t1 = setTimeout(() => setRisen(true),  350);
    const t2 = setTimeout(() => setLanded(true), 1500);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);

  return (
    <div className="ax-fade-in" style={{
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      padding: '24px 24px 20px', gap: 28,
    }}>

      {/* LEFT — original stays locked on device */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, marginTop: 10 }}>
        <div style={{ position: 'relative' }}>
          <DLaptopFrame compact>
            <DPolicyCardSmall
              nombre={real.nombre} rfc={real.rfc} fnac={real.fnac}
              struct={struct} dimmed
            />
          </DLaptopFrame>
          {/* Lock badge */}
          <div style={{
            position: 'absolute', top: 5, right: -11,
            width: 24, height: 24, borderRadius: '50%',
            background: 'var(--ax-bg)',
            border: '1px solid var(--ax-border-strong)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--ax-warm)',
          }}>
            <AxIcon name="eye-off" size={11}/>
          </div>
        </div>
        <div style={{
          fontSize: 9, color: 'var(--ax-fg-faint)', textAlign: 'center',
          lineHeight: 1.45, maxWidth: 120,
        }}>
          Nunca sale de<br/>tu equipo
        </div>
      </div>

      {/* Center arrow */}
      <div style={{ marginTop: 64, color: 'var(--ax-fg-faint)' }}>
        <AxIcon name="arrow-right" size={14}/>
      </div>

      {/* RIGHT — masked copy rises toward cloud */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>

        {/* Cloud target */}
        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          padding: '10px 20px',
          background: landed ? 'var(--ax-accent-soft)' : 'var(--ax-bg-3)',
          border: '1px solid ' + (landed ? 'var(--ax-accent-line)' : 'var(--ax-border)'),
          borderRadius: 10,
          transition: 'background 600ms, border-color 600ms',
        }}>
          <AxIcon name="cloud" size={22} style={{
            color: landed ? 'var(--ax-accent)' : 'var(--ax-fg-muted)',
            transition: 'color 600ms',
          }}/>
          <span style={{
            fontSize: 8, letterSpacing: '0.14em', textTransform: 'uppercase',
            fontFamily: 'var(--font-mono)',
            color: landed ? 'var(--ax-accent)' : 'var(--ax-fg-faint)',
            transition: 'color 600ms',
          }}>Piixi</span>
        </div>

        {/* Arrow up */}
        <div style={{
          color: risen ? 'var(--ax-accent)' : 'var(--ax-fg-faint)',
          transition: 'color 600ms',
        }}>
          <AxIcon name="arrow-up" size={12}/>
        </div>

        {/* Masked card — animates upward */}
        <div style={{
          transform: risen ? 'translateY(0)' : 'translateY(36px)',
          opacity: risen ? 1 : 0,
          transition: 'transform 950ms cubic-bezier(0.16,1,0.3,1), opacity 550ms',
        }}>
          <DPolicyCardSmall
            nombre={fake.nombre} rfc={fake.rfc} fnac={fake.fnac}
            struct={struct} masked
          />
        </div>
      </div>
    </div>
  );
}

// ─── Beat 4: Piixi learned the format, not the people ────────────────────────
function DLBeat4() {
  return (
    <div className="ax-fade-in" style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: '36px 24px 28px', gap: 14, minHeight: 220,
    }}>
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
        padding: '20px 36px',
        background: 'var(--ax-accent-soft)',
        border: '1px solid var(--ax-accent-line)',
        borderRadius: 14,
      }}>
        <AxIcon name="cloud" size={32} style={{ color: 'var(--ax-accent)' }}/>
        <span style={{
          fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase',
          fontFamily: 'var(--font-mono)', color: 'var(--ax-accent)',
        }}>Piixi</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
          <AxIcon name="check" size={14} style={{ color: 'var(--ax-accent)' }}/>
          <span style={{ fontSize: 13, color: 'var(--ax-fg-strong)', fontWeight: 500 }}>
            regla aprendida
          </span>
        </div>
      </div>
      <div style={{
        fontSize: 12, color: 'var(--ax-fg-muted)', textAlign: 'center',
        maxWidth: 320, lineHeight: 1.55,
      }}>
        El modelo reconoce el formato de este documento. Las personas nunca cruzan.
      </div>
    </div>
  );
}

// ─── Compact consent block ────────────────────────────────────────────────────
function DLConsentBlock({ consent, setConsent, saved, onSave }) {
  return (
    <div style={{
      background: 'var(--ax-bg-2)',
      border: '1px solid var(--ax-border-strong)',
      borderRadius: 10, padding: '16px 18px',
    }}>
      <label style={{
        display: 'flex', alignItems: 'center', gap: 10,
        cursor: 'default', marginBottom: 14,
      }}>
        <input
          type="checkbox"
          checked={consent}
          onChange={(e) => setConsent(e.target.checked)}
          style={{ accentColor: 'var(--ax-accent)', width: 14, height: 14, flexShrink: 0 }}
        />
        <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>
          Autorizo el envío de versiones enmascaradas
        </span>
      </label>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <AxButton
          variant="primary"
          icon={saved ? 'check' : 'shield'}
          onClick={onSave}
        >
          {saved
            ? (consent ? 'Autorización activa' : 'Preferencia guardada')
            : 'Guardar preferencia'}
        </AxButton>
        <span style={{ fontSize: 11, color: 'var(--ax-fg-faint)' }}>
          Opt-in y revocable cuando quieras.
        </span>
      </div>
    </div>
  );
}

// ─── Main screen ──────────────────────────────────────────────────────────────
function DiscoveryLoopScreen() {
  const prefersReduced =
    typeof window !== 'undefined' &&
    window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const [beat, setBeat]       = useState(prefersReduced ? 3 : 0);
  const [autoPlay, setAutoPlay] = useState(!prefersReduced);
  const [consent, setConsent] = useState(false);
  const [saved, setSaved]     = useState(false);
  const { navigate }          = useHashRoute();

  // Advance beats 0 → 1 → 2 → 3, then stop
  useEffect(() => {
    if (!autoPlay) return;
    if (beat >= 3) { setAutoPlay(false); return; }
    const DURS = [3000, 3600, 3600];
    const t = setTimeout(() => setBeat((b) => b + 1), DURS[beat]);
    return () => clearTimeout(t);
  }, [beat, autoPlay]);

  const replay = () => { setBeat(0); setAutoPlay(true); };
  const goTo   = (n) => { setBeat(n); setAutoPlay(false); };

  const CAPTIONS = [
    'Tu póliza, en tu equipo.',
    'Cambiamos el valor, no la forma.',
    'Solo sale la forma.',
    'Piixi aprende el formato, no se lleva a las personas.',
  ];

  const REAL = {
    nombre: 'Juan Pérez López',
    rfc:    'LOPJ800515AB1',
    fnac:   '15/05/1980',
    tel:    '55-1234-5678',
    poliza: '9000001',
  };
  const FAKE = {
    nombre: 'Carlos Ramírez Torres',
    rfc:    'RATC750322XY7',
    fnac:   '22/03/1975',
    tel:    '55-9876-1234',
    poliza: '7341829',
  };
  const STRUCT = {
    producto: 'GMM · Plan Protección Total',
    prima:    '$12,500.00',
    vigencia: '01/01/2026 – 01/01/2027',
  };

  return (
    <div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
      <AxPageHeader
        eyebrow="Configuración · Discovery Loop"
        title="Aprendizaje colaborativo"
        actions={
          <AxButton
            variant="tertiary" size="sm" icon="arrow-left"
            onClick={() => navigate('/ajustes')}
          >
            Ajustes
          </AxButton>
        }
      />

      <div style={{ flex: 1, padding: '28px 32px 48px' }}>
        <div style={{ maxWidth: 680, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 20 }}>

          {/* ── Animation stage ─────────────────────────────────── */}
          <div style={{
            background: 'var(--ax-bg-2)',
            border: '1px solid var(--ax-border)',
            borderRadius: 14,
            overflow: 'hidden',
          }}>

            {/* Caption + replay control */}
            <div style={{
              padding: '12px 18px 10px',
              borderBottom: '1px solid var(--ax-border)',
              display: 'flex', alignItems: 'center',
              justifyContent: 'space-between', gap: 12,
            }}>
              <div
                key={beat}
                className="ax-fade-in"
                style={{
                  fontSize: 15, fontWeight: 600,
                  color: 'var(--ax-fg-strong)', letterSpacing: '-0.01em',
                }}
              >
                {CAPTIONS[beat]}
              </div>
              {!autoPlay && (
                <button onClick={replay} className="ax-btn ax-btn--tertiary ax-btn--sm">
                  <AxIcon name="play" size={11}/>
                  <span>Volver a ver</span>
                </button>
              )}
            </div>

            {/* Beat stage */}
            <div style={{ minHeight: 260 }}>
              {beat === 0 && <DLBeat1 real={REAL} struct={STRUCT}/>}
              {beat === 1 && <DLBeat2 real={REAL} fake={FAKE} struct={STRUCT}/>}
              {beat === 2 && <DLBeat3 real={REAL} fake={FAKE} struct={STRUCT}/>}
              {beat === 3 && <DLBeat4/>}
            </div>

            {/* Beat dot indicators */}
            <div style={{
              padding: '8px 18px 10px',
              borderTop: '1px solid var(--ax-border)',
              display: 'flex', alignItems: 'center', gap: 7,
            }}>
              {[0, 1, 2, 3].map((n) => (
                <button
                  key={n}
                  onClick={() => goTo(n)}
                  title={'Beat ' + (n + 1)}
                  style={{
                    width: beat === n ? 20 : 6,
                    height: 6, borderRadius: 3,
                    border: 'none', padding: 0,
                    background: beat === n ? 'var(--ax-accent)' : 'var(--ax-border-strong)',
                    cursor: 'default',
                    transition: 'width 250ms cubic-bezier(0.16,1,0.3,1), background 250ms',
                  }}
                />
              ))}
            </div>
          </div>

          {/* ── Consent action ──────────────────────────────────── */}
          <DLConsentBlock
            consent={consent}
            setConsent={(v) => { setConsent(v); setSaved(false); }}
            saved={saved}
            onSave={() => setSaved(true)}
          />

        </div>
      </div>
    </div>
  );
}

window.DiscoveryLoopScreen = DiscoveryLoopScreen;
