// Credit Midas — Single-page landing (Origin-inspired, adapted)
// Single composition; mobile-first via CSS. Uses useT() for bilingual.

const { useState, useEffect, useRef, useMemo } = React;

// ─── Bilingual context ──────────────────────────────────────────
const LangContext = React.createContext(['es', () => {}]);
const useLang = () => React.useContext(LangContext);
const useT = () => {
  const [lang] = useLang();
  return (es, en) => (lang === 'es' ? es : en);
};

const LangProvider = ({ children }) => {
  const [lang, setLang] = React.useState(() => {
    try { return localStorage.getItem('midas.lang') || 'es'; } catch { return 'es'; }
  });
  React.useEffect(() => {
    try { localStorage.setItem('midas.lang', lang); } catch {}
  }, [lang]);
  return (
    <LangContext.Provider value={[lang, setLang]}>{children}</LangContext.Provider>
  );
};

const LangSwitch = () => {
  const [lang, setLang] = useLang();
  return (
    <div className="cm-lang" role="group" aria-label="Idioma / Language">
      <button type="button"
        className={lang === 'es' ? 'on' : ''}
        onClick={() => setLang('es')}
        aria-pressed={lang === 'es'}>ES</button>
      <button type="button"
        className={lang === 'en' ? 'on' : ''}
        onClick={() => setLang('en')}
        aria-pressed={lang === 'en'}>EN</button>
    </div>
  );
};

// ─── Reveal wrapper — fades in on scroll ────────────────────────
const Reveal = ({ children, delay = 0, as: As = 'div', className = '', style }) => {
  const ref = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setVis(true); io.disconnect(); }
    }, { threshold: 0.18 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <As ref={ref}
        className={`cm-reveal ${vis ? 'in' : ''} ${className}`}
        style={{ transitionDelay: `${delay}ms`, ...style }}>
      {children}
    </As>
  );
};

// ─── CountUp ─────────────────────────────────────────────────────
const easeOut = t => 1 - Math.pow(1 - t, 3);
const CountUp = ({ to = 732, from = 0, duration = 1600, delay = 200 }) => {
  const ref = useRef(null);
  const [v, setV] = useState(from);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (!e.isIntersecting) return;
      io.disconnect();
      let raf, start;
      const t0 = setTimeout(() => {
        const tick = ts => {
          if (!start) start = ts;
          const p = Math.min(1, (ts - start) / duration);
          setV(from + (to - from) * easeOut(p));
          if (p < 1) raf = requestAnimationFrame(tick);
        };
        raf = requestAnimationFrame(tick);
      }, delay);
      return () => { clearTimeout(t0); cancelAnimationFrame(raf); };
    }, { threshold: 0.3 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return <span ref={ref}>{Math.round(v).toLocaleString('en-US')}</span>;
};

// ─── AnimatedBar ────────────────────────────────────────────────
const AnimatedBar = ({ to = 62, delay = 400, duration = 1700 }) => {
  const ref = useRef(null);
  const [w, setW] = useState(0);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        io.disconnect();
        setTimeout(() => setW(to), delay);
      }
    }, { threshold: 0.3 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <div className="cm-score-bar" ref={ref} style={{ marginTop: 22 }}>
      <div className="fill" style={{
        width: `${w}%`,
        transition: `width ${duration}ms cubic-bezier(.22,.61,.36,1)`,
      }} />
      <div className="marker" style={{
        left: `${w}%`,
        transition: `left ${duration}ms cubic-bezier(.22,.61,.36,1)`,
      }} />
    </div>
  );
};

// ─── Atmospheric hero background ────────────────────────────────
// Ambient looping MP4 with the editorial grain overlaid on top
// to preserve the film-texture look.
const HeroBackground = () => (
  <>
    <div className="cm-hero-bg" aria-hidden="true">
      <video
        className="cm-hero-video"
        src="hero-bg.mp4"
        autoPlay
        loop
        muted
        playsInline
        preload="auto"
        aria-hidden="true"
      />
    </div>
    <svg className="cm-grain" aria-hidden="true">
      <filter id="cm-grain-f">
        <feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2" stitchTiles="stitch" />
        <feColorMatrix values="0 0 0 0 0   0 0 0 0 0   0 0 0 0 0   0 0 0 1 0" />
      </filter>
      <rect width="100%" height="100%" filter="url(#cm-grain-f)" />
    </svg>
  </>
);

// ─── Score card (animated) ──────────────────────────────────────
const ScoreCard = ({ compact = false }) => {
  const t = useT();
  return (
    <div className="cm-score-card" style={compact ? { padding: 22 } : null}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
        <div>
          <div className="cm-score-mono">
            {t('SCORE PROMEDIO · CLIENTE MIDAS', 'AVERAGE SCORE · MIDAS CLIENT')}
          </div>
          <div className="cm-score-num" style={{ marginTop: 8 }}>
            <CountUp to={732} />
            <span style={{ fontSize: '.32em', color: 'var(--gold)', marginLeft: 8 }}>↑</span>
          </div>
          <div className="cm-score-delta" style={{ marginTop: 6 }}>
            + <CountUp to={148} /> PTS &nbsp;·&nbsp; {t('6 MESES', '6 MONTHS')}
          </div>
        </div>
        <div className="cm-score-mono" style={{
          border: '1px solid oklch(0.42 0.02 60)',
          padding: '5px 10px', borderRadius: 4,
          whiteSpace: 'nowrap',
        }}>
          n = <CountUp to={412} />
        </div>
      </div>

      <AnimatedBar to={62} />

      <div className="cm-score-axis" style={{ marginTop: 8 }}>
        <span>300</span><span>POOR</span><span>FAIR</span><span>GOOD</span><span>850</span>
      </div>
    </div>
  );
};

// ─── Phone mockup with chat ─────────────────────────────────────
const PhoneChat = () => {
  const t = useT();
  return (
    <div className="cm-phone">
      <div className="cm-phone-screen">
        <div className="cm-phone-notch"></div>
        <div style={{
          height: 56,
          display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
          paddingBottom: 6,
          fontFamily: 'var(--mono)', fontSize: 10.5,
          color: 'var(--ink-faint)', letterSpacing: '.06em',
        }}>
          MIDAS · WHATSAPP BOT
        </div>
        <hr style={{ border: 0, borderTop: '1px solid var(--rule)', margin: 0 }} />
        <div className="cm-chat">
          <div className="cm-bubble in">
            <span className="name">Midas Bot</span>
            {t('¡Hola! Mándame tu reporte (PDF o screenshot) y lo analizamos al instante.',
               'Hi! Send me your report (PDF or screenshot) and I\'ll analyze it on the spot.')}
          </div>
          <div className="cm-bubble out">
            <span className="name">{t('Tú', 'You')}</span>
            📎 credit-report.pdf
          </div>
          <div className="cm-bubble in">
            <span className="name">Midas Bot</span>
            {t(
              'Encontré 3 cuentas negativas disputables y 1 collector vencido. ¿Quieres tu plan?',
              'Found 3 disputable negatives and 1 expired collector. Want your plan?'
            )}
          </div>
          <div className="cm-bubble out" style={{ background: 'var(--gold-deep)', color: 'var(--cream)' }}>
            <span className="name" style={{ color: 'oklch(0.92 0.014 60)' }}>{t('Tú', 'You')}</span>
            {t('Sí. Mándalo.', 'Yes. Send it.')}
          </div>
        </div>
      </div>
    </div>
  );
};

// ─── Nav ────────────────────────────────────────────────────────
const Nav = () => {
  const t = useT();
  return (
    <nav className="cm-nav">
      <div className="cm-nav-inner">
        <a href="#top" className="cm-wordmark">
          Midas<span className="slash">/</span>credit
          <span className="suffix">EST. 2026</span>
        </a>
        <div className="cm-nav-links">
          <a href="#lee">{t('Cómo funciona', 'How it works')}</a>
          <a href="#planes">{t('Planes', 'Plans')}</a>
          <a href="#joel">{t('Historia', 'Story')}</a>
          <a href="#faq">FAQ</a>
        </div>
        <div className="cm-nav-right">
          <LangSwitch />
          <a href="#cta" className="cm-btn cm-btn-sm">
            {t('Empezar gratis', 'Start free')}
            <span className="arrow">→</span>
          </a>
        </div>
      </div>
    </nav>
  );
};

// ─── Hero ───────────────────────────────────────────────────────
const Hero = () => {
  const t = useT();
  return (
    <section className="cm-hero" id="top">
      <HeroBackground />
      <div className="cm-hero-inner">
        <Reveal>
          <div className="cm-hero-pill">
            <span className="dot"></span>
            {t('Edición limitada · 200 cupos · Q1 2026', 'Limited edition · 200 spots · Q1 2026')}
          </div>
        </Reveal>

        <Reveal delay={120}>
          <h1 className="cm-display cm-h1">
            {t(
              <>Tu crédito ya no es de&nbsp;<em>nadie más.</em></>,
              <>Your credit isn't anyone&nbsp;<em>else's anymore.</em></>
            )}
          </h1>
        </Reveal>

        <Reveal delay={240}>
          <p className="cm-lede cm-hero-lede">
            {t(
              'El sistema, las cartas, los derechos legales — en tus manos, en tu idioma, por una décima parte de lo que cobran las agencias.',
              'The system, the letters, the legal rights — in your hands, in your language, for a tenth of what the agencies charge.'
            )}
          </p>
        </Reveal>

        <Reveal delay={340}>
          <div className="cm-hero-actions">
            <a href="#cta" className="cm-btn cm-btn-lg">
              {t('Tomar el control', 'Take control')}
              <span className="arrow">→</span>
            </a>
            <a href="#lee" className="cm-link">{t('Ver cómo funciona · 60 seg', 'See how it works · 60 sec')}</a>
          </div>
        </Reveal>

        <Reveal delay={420}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            fontFamily: 'var(--serif)', fontStyle: 'italic',
            fontSize: 15, lineHeight: 1.45,
            color: 'var(--ink-soft)',
            maxWidth: 540,
          }}>
            <span style={{ color: 'var(--gold-deep)', fontStyle: 'normal' }}>✓</span>
            {t(
              'Con garantía de 30 días money-back: si el informe no aporta valor, te devuelvo el 100%.',
              '30-day money-back guarantee: if the report doesn\'t add value, I refund 100%.'
            )}
          </div>
        </Reveal>

        <Reveal delay={460}>
          <div className="cm-hero-tagline">
            {t('Analiza todo. Disputa todo.', 'Analyze everything. Dispute everything.')}
          </div>
        </Reveal>

        <Reveal delay={580} style={{ marginTop: 12 }}>
          <PhoneChat />
        </Reveal>
      </div>
    </section>
  );
};

// ─── Simplify intro (small lead-in) ─────────────────────────────
const SimplifyIntro = () => {
  const t = useT();
  return (
    <section className="cm-section" style={{ paddingTop: 0, textAlign: 'center' }}>
      <Reveal>
        <div className="cm-section-eyebrow" style={{ textAlign: 'center' }}>
          {t('Simplifica tu crédito', 'Simplify your credit')}
        </div>
      </Reveal>
    </section>
  );
};

// ─── Section: Lee todo (feature trio) ───────────────────────────
const SectionLee = () => {
  const t = useT();
  return (
    <section className="cm-section" id="lee">
      <header className="cm-section-header">
        <Reveal>
          <div className="cm-section-eyebrow">{t('Lee todo', 'Read everything')}</div>
        </Reveal>
        <Reveal delay={120}>
          <h2 className="cm-display cm-h2">
            {t(
              <><em>Entiende</em> tu reporte<br/>como nunca antes.</>,
              <><em>Understand</em> your report<br/>like never before.</>
            )}
          </h2>
        </Reveal>
        <Reveal delay={220}>
          <p className="cm-lede" style={{ maxWidth: 600 }}>
            {t(
              'Subes el PDF. Te decimos qué se puede atacar, qué se puede negociar y qué no toca. En español, sin tecnicismos vacíos.',
              'Upload your PDF. We tell you what can be challenged, what can be negotiated, and what to leave alone. In plain language, no empty jargon.'
            )}
          </p>
        </Reveal>
      </header>

      <div className="cm-feature-row">
        <Reveal>
          <article className="cm-feature-card">
            <div className="preview">
              <FeatureReport />
            </div>
            <div className="cm-mono">01 · {t('ANÁLISIS', 'ANALYSIS')}</div>
            <h3>{t('Análisis al instante', 'Instant analysis')}</h3>
            <p>{t(
              'Cuentas negativas, positivas, items disputables — todo identificado en minutos, no en semanas.',
              'Negatives, positives, disputable items — all flagged in minutes, not weeks.'
            )}</p>
          </article>
        </Reveal>

        <Reveal delay={120}>
          <article className="cm-feature-card">
            <div className="preview">
              <FeatureLetter />
            </div>
            <div className="cm-mono">02 · {t('CARTAS', 'LETTERS')}</div>
            <h3>{t('Cartas listas para enviar', 'Letters ready to send')}</h3>
            <p>{t(
              'Disputa, validation, cease & desist. Plantillas basadas en formatos legales protegidos por FCRA y FDCPA. Listas para personalizar y enviar — y si quieres, revísalas con tu abogado de confianza antes de mandarlas.',
              'Dispute, validation, cease & desist. Templates based on legal formats protected by FCRA and FDCPA. Ready to personalize and send — and if you want, review them with your trusted attorney before mailing.'
            )}</p>
          </article>
        </Reveal>

        <Reveal delay={240}>
          <article className="cm-feature-card">
            <div className="preview">
              <FeatureTimeline />
            </div>
            <div className="cm-mono">03 · {t('PLAN', 'PLAN')}</div>
            <h3>{t('Plan paso a paso', 'Step-by-step plan')}</h3>
            <p>{t(
              'Semana 1, mes 1, mes 3. Qué enviar, cuándo enviarlo, qué esperar. Si te trabas, te escribo personal.',
              'Week 1, month 1, month 3. What to send, when to send it, what to expect. Stuck? I write you directly.'
            )}</p>
          </article>
        </Reveal>
      </div>
    </section>
  );
};

// ─── Feature mini-mockups (SVG-ish UI) ──────────────────────────
const FeatureReport = () => {
  const t = useT();
  return (
    <div style={{ position: 'absolute', inset: 16, fontFamily: 'var(--sans)' }}>
      <div className="cm-mono" style={{ marginBottom: 8 }}>
        REPORT · EQUIFAX · 09-2026
      </div>
      {[
        { label: t('Tarjeta Capital One', 'Capital One Card'),  v: '–$1,240', neg: true },
        { label: t('Préstamo auto Ford',  'Ford Auto Loan'),    v: '–$8,300', neg: true },
        { label: t('Macy\'s · charge-off','Macy\'s · charge-off'), v: '–$640',   neg: true },
        { label: t('Discover · al día',   'Discover · current'), v: '+$420',   neg: false },
      ].map((r, i) => (
        <div key={i} style={{
          display: 'flex', justifyContent: 'space-between',
          padding: '7px 0',
          borderBottom: '1px dashed var(--rule)',
          fontSize: 12,
          color: r.neg ? 'oklch(0.45 0.10 25)' : 'oklch(0.42 0.10 145)',
        }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>
            <span style={{
              width: 7, height: 7, borderRadius: 999,
              background: r.neg ? 'oklch(0.55 0.18 25)' : 'oklch(0.55 0.18 145)',
              flex: '0 0 auto',
            }} />
            {r.label}
          </span>
          <span style={{ fontFamily: 'var(--mono)' }}>{r.v}</span>
        </div>
      ))}
      <div style={{
        marginTop: 12, padding: '8px 10px',
        background: 'var(--ink)', color: 'var(--gold)',
        borderRadius: 6, fontSize: 11,
        fontFamily: 'var(--mono)', letterSpacing: '.04em',
      }}>
        3 {t('DISPUTABLES', 'DISPUTABLE')}  ·  1 SOL {t('VENCIDO', 'EXPIRED')}
      </div>
    </div>
  );
};

const FeatureLetter = () => {
  const t = useT();
  return (
    <div style={{
      position: 'absolute', inset: 16,
      background: 'var(--paper)',
      borderRadius: 8,
      border: '1px solid var(--rule)',
      padding: 14,
      fontFamily: 'var(--serif)',
      fontSize: 11,
      color: 'var(--ink-soft)',
      overflow: 'hidden',
    }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-faint)', marginBottom: 8 }}>
        DISPUTE · FCRA §611
      </div>
      <div style={{ marginBottom: 6, color: 'var(--ink)' }}>To: Equifax Information Services</div>
      <div style={{ marginBottom: 10, color: 'var(--ink)' }}>Re: Disputed account #****-4127</div>
      {[
        'I am writing to formally dispute the following inaccurate',
        'information on my consumer report under §611 of the',
        'Fair Credit Reporting Act. Please investigate and',
        'remove the item within 30 days as required by law.',
      ].map((l, i) => (
        <div key={i} style={{ marginBottom: 2 }}>{l}</div>
      ))}
      <div style={{ marginTop: 12, fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--gold-deep)' }}>
        ✓ {t('AUTO-RELLENADO CON TUS DATOS', 'AUTO-FILLED WITH YOUR DATA')}
      </div>
    </div>
  );
};

const FeatureTimeline = () => {
  const t = useT();
  return (
    <div style={{ position: 'absolute', inset: 16, fontFamily: 'var(--sans)' }}>
      <div className="cm-mono" style={{ marginBottom: 10 }}>
        {t('TU PLAN · 90 DÍAS', 'YOUR PLAN · 90 DAYS')}
      </div>
      {[
        [t('Semana 1', 'Week 1'),  t('Enviar 3 disputas', 'Send 3 disputes'),  true],
        [t('Mes 1',    'Month 1'), t('Validation a collector', 'Validation to collector'), true],
        [t('Mes 2',    'Month 2'), t('Revisar respuestas', 'Review responses'), false],
        [t('Mes 3',    'Month 3'), t('Cambios en buró', 'Bureau updates'), false],
      ].map(([when, what, done], i) => (
        <div key={i} style={{
          display: 'flex', gap: 10, alignItems: 'center',
          padding: '6px 0',
          borderBottom: '1px dashed var(--rule)',
          fontSize: 12,
        }}>
          <span style={{
            width: 14, height: 14, borderRadius: 999,
            border: '1.5px solid var(--ink)',
            background: done ? 'var(--ink)' : 'transparent',
            color: 'var(--cream)',
            fontSize: 9, display: 'grid', placeItems: 'center',
            flex: '0 0 auto',
          }}>{done ? '✓' : ''}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-faint)', minWidth: 60 }}>
            {when}
          </span>
          <span style={{ color: 'var(--ink)' }}>{what}</span>
        </div>
      ))}
    </div>
  );
};

Object.assign(window, {
  LangContext, LangProvider, LangSwitch, useLang, useT,
  Reveal, CountUp, AnimatedBar,
  HeroBackground, ScoreCard, PhoneChat,
  Nav, Hero, SimplifyIntro, SectionLee,
  FeatureReport, FeatureLetter, FeatureTimeline,
});
