// KineSuite landing — extra sections: animated hero phone,
// clinics (B2B), changelog, cookie banner.

const { useState: useS, useEffect: useE, useRef: useR } = React;

function usePhoneWidth(max = 360, min = 260) {
  const [w, setW] = useS(max);
  useE(() => {
    const update = () => {
      const next = Math.min(max, Math.max(min, window.innerWidth - 48));
      setW(next);
    };
    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, [max, min]);
  return w;
}

function HeroMockDisclaimer({ lang }) {
  const text = LANDING_COPY[lang].heroMockDisclaimer;
  return (
    <p style={{
      margin: 0,
      maxWidth: 300,
      textAlign: 'center',
      fontSize: 11,
      lineHeight: 1.45,
      color: 'var(--gray-500)',
      letterSpacing: '0.01em',
    }}>
      {text}
    </p>
  );
}

function HeroPhoneStack({ lang, width: widthProp, animated, children }) {
  const responsiveW = usePhoneWidth();
  const width = widthProp != null ? Math.min(widthProp, responsiveW) : responsiveW;
  return (
    <div className="phone-frame-wrap" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
      {animated ? (
        <AnimatedHeroPhone lang={lang} width={width} />
      ) : (
        <LandingPhone width={width}>{children}</LandingPhone>
      )}
      <HeroMockDisclaimer lang={lang} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// AnimatedHeroPhone — auto-cycles through 3 app screens
// Catalog → Eval → Result → loop, with a crossfade and a
// play/pause control. Keeps the same LandingPhone bezel.
// ─────────────────────────────────────────────────────────────
function AnimatedHeroPhone({ lang, width = 360 }) {
  const screens = ['catalog', 'eval', 'result'];
  const labels = {
    es: { catalog: 'Catálogo', eval: 'Evaluación · Berg', result: 'Resultado' },
    en: { catalog: 'Library',  eval: 'Assessment · Berg', result: 'Result'    },
  };
  const [idx, setIdx] = useS(0);
  const [paused, setPaused] = useS(false);

  useE(() => {
    if (paused) return;
    const id = setInterval(() => setIdx((i) => (i + 1) % screens.length), 3400);
    return () => clearInterval(id);
  }, [paused]);

  const renderScreen = (kind) => {
    if (kind === 'eval')   return <LandingEvalScreen lang={lang} />;
    if (kind === 'result') return <LandingResultScreen lang={lang} />;
    return <LandingCatalogScreen lang={lang} />;
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
      <LandingPhone width={width}>
        {/* Crossfade stack: all 3 screens, the active one is opacity 1 */}
        {screens.map((s, i) => (
          <div key={s} style={{
            position: 'absolute', inset: 0,
            opacity: i === idx ? 1 : 0,
            transition: 'opacity 0.45s ease',
            pointerEvents: i === idx ? 'auto' : 'none',
          }}>
            {renderScreen(s)}
          </div>
        ))}
      </LandingPhone>

      {/* Step indicator + play / pause */}
      <div className="hero-controls" style={{
        display: 'flex', alignItems: 'center', gap: 16,
        padding: '8px 14px',
        borderRadius: 999,
        background: 'var(--paper)',
        border: '1px solid var(--gray-200)',
        boxShadow: 'var(--shadow-card)',
      }}>
        <button
          onClick={() => setPaused((p) => !p)}
          aria-label={paused ? 'Play' : 'Pause'}
          style={{
            width: 22, height: 22, borderRadius: 999,
            border: 'none', background: 'var(--ink)', color: 'var(--paper)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', padding: 0,
          }}
        >
          {paused ? (
            <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z" /></svg>
          ) : (
            <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor">
              <rect x="6" y="5" width="4" height="14" rx="1" />
              <rect x="14" y="5" width="4" height="14" rx="1" />
            </svg>
          )}
        </button>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          {screens.map((s, i) => (
            <button
              key={s}
              onClick={() => setIdx(i)}
              aria-label={labels[lang][s]}
              style={{
                width: i === idx ? 24 : 6, height: 6, borderRadius: 4,
                background: i === idx ? 'var(--primary)' : 'var(--gray-300)',
                border: 'none', padding: 0, cursor: 'pointer',
                transition: 'width 0.25s ease, background 0.25s ease',
              }}
            />
          ))}
        </div>
        <div className="hero-controls-label" style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 10.5, fontWeight: 600,
          color: 'var(--gray-500)', letterSpacing: '0.06em',
          minWidth: 110,
        }}>
          {labels[lang][screens[idx]].toUpperCase()}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ClinicsSection — B2B card, different visual treatment
// ─────────────────────────────────────────────────────────────
function ClinicsSection({ t, lang }) {
  return (
    <section id="clinicas">
      <div className="container">
        <div className="clinics-panel">
          {/* Decorative arc, brand mark echoed top-right */}
          <div style={{
            position: 'absolute',
            top: -120, right: -120,
            width: 360, height: 360,
            borderRadius: '50%',
            border: '1px solid color-mix(in oklab, var(--paper) 14%, transparent)',
            pointerEvents: 'none',
          }} />
          <div style={{
            position: 'absolute',
            top: -60, right: -60,
            width: 240, height: 240,
            borderRadius: '50%',
            border: '1px solid color-mix(in oklab, var(--paper) 10%, transparent)',
            pointerEvents: 'none',
          }} />

          <div style={{ display: 'flex', flexDirection: 'column', gap: 22, position: 'relative' }}>
            <div className="eyebrow" style={{ color: 'color-mix(in oklab, var(--paper) 60%, transparent)' }}>
              {t.clinicsEyebrow}
            </div>
            <h2 className="section-title" style={{ color: 'var(--paper)' }}>
              {t.clinicsTitle}
            </h2>
            <p style={{ color: 'color-mix(in oklab, var(--paper) 80%, transparent)', fontSize: 17, lineHeight: 1.55, maxWidth: '48ch' }}>
              {t.clinicsSub}
            </p>

            <div style={{ display: 'flex', gap: 12, marginTop: 12, flexWrap: 'wrap' }}>
              <a href={`mailto:${t.clinicsEmail}`} className="btn"
                 style={{ background: 'var(--paper)', color: 'var(--ink)' }}>
                {t.clinicsCtaPrimary} →
              </a>
              <a href={`mailto:${t.clinicsEmail}`} className="btn"
                 style={{ background: 'transparent', color: 'var(--paper)', border: '1px solid color-mix(in oklab, var(--paper) 30%, transparent)' }}>
                {t.clinicsCtaSecondary}
              </a>
            </div>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
              color: 'color-mix(in oklab, var(--paper) 60%, transparent)',
              marginTop: 4,
            }}>
              {t.clinicsEmail}
            </div>
          </div>

          <ul style={{
            listStyle: 'none', padding: 0, margin: 0,
            display: 'flex', flexDirection: 'column', gap: 0,
            position: 'relative',
          }}>
            {t.clinicsFeatures.map((f, i) => (
              <li key={i} style={{
                display: 'grid',
                gridTemplateColumns: '36px 1fr',
                gap: 16,
                padding: '20px 0',
                borderTop: i === 0 ? '1px solid color-mix(in oklab, var(--paper) 14%, transparent)' : 'none',
                borderBottom: '1px solid color-mix(in oklab, var(--paper) 14%, transparent)',
                alignItems: 'flex-start',
              }}>
                <div style={{
                  fontFamily: 'JetBrains Mono, monospace',
                  fontSize: 11, fontWeight: 700,
                  color: 'var(--primary)',
                  letterSpacing: '0.08em',
                  marginTop: 2,
                }}>
                  ·{String(i + 1).padStart(2,'0')}
                </div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 17, color: 'var(--paper)', letterSpacing: '-0.015em' }}>
                    {f.t}
                  </div>
                  <div style={{ marginTop: 4, fontSize: 14, color: 'color-mix(in oklab, var(--paper) 70%, transparent)', lineHeight: 1.5 }}>
                    {f.d}
                  </div>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// ChangelogSection — timeline of versions
// ─────────────────────────────────────────────────────────────
function ChangelogSection({ t }) {
  return (
    <section id="changelog">
      <div className="container">
        <div className="layout-changelog">
          <div className="layout-sticky-side">
            <h2 className="section-title">{t.changelogTitle}</h2>
            <p className="lead">{t.changelogSub}</p>
          </div>

          <ol style={{
            listStyle: 'none', padding: 0, margin: 0,
            display: 'flex', flexDirection: 'column',
          }}>
            {t.changelogItems.map((v, i) => {
              const isFirst = i === 0;
              return (
                <li key={i} className="changelog-entry" style={{
                  display: 'grid',
                  gridTemplateColumns: '140px 1fr',
                  gap: 28,
                  padding: '28px 0',
                  borderTop: i === 0 ? '1px solid var(--gray-200)' : 'none',
                  borderBottom: '1px solid var(--gray-200)',
                  position: 'relative',
                }}>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    <div style={{
                      fontFamily: 'JetBrains Mono, monospace',
                      fontSize: 13, fontWeight: 700,
                      color: 'var(--ink)', letterSpacing: '0.04em',
                    }}>
                      {v.version}
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--gray-500)' }}>
                      {v.date}
                    </div>
                    {isFirst && (
                      <span style={{
                        marginTop: 6,
                        display: 'inline-flex', alignItems: 'center', gap: 5,
                        fontFamily: 'JetBrains Mono, monospace', fontSize: 9.5,
                        padding: '3px 8px', borderRadius: 999,
                        background: 'var(--primary-100)', color: 'var(--primary)',
                        letterSpacing: '0.1em', textTransform: 'uppercase',
                        fontWeight: 700, width: 'fit-content',
                      }}>
                        <span style={{ width: 5, height: 5, borderRadius: 999, background: 'var(--primary)' }} />
                        {t.changelogLatest}
                      </span>
                    )}
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <div style={{ fontWeight: 700, fontSize: 19, color: 'var(--ink)', letterSpacing: '-0.025em' }}>
                      {v.title}
                    </div>
                    <ul style={{
                      listStyle: 'none', padding: 0, margin: 0,
                      display: 'flex', flexDirection: 'column', gap: 6,
                    }}>
                      {v.notes.map((n, j) => (
                        <li key={j} style={{
                          display: 'flex', gap: 10, alignItems: 'flex-start',
                          fontSize: 14, color: 'var(--gray-700)', lineHeight: 1.5,
                        }}>
                          <span style={{
                            flexShrink: 0, marginTop: 8,
                            width: 4, height: 4, borderRadius: 2,
                            background: v.kind === 'planned' ? 'var(--gray-300)' : 'var(--primary)',
                          }} />
                          <span>{n}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </li>
              );
            })}
          </ol>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// CookieBanner — minimal, dismissible, persists via localStorage
// ─────────────────────────────────────────────────────────────
function CookieBanner({ t }) {
  const [visible, setVisible] = useS(false);
  const [details, setDetails] = useS(false);

  useE(() => {
    try {
      const accepted = localStorage.getItem('kinesuite-cookies');
      if (!accepted) {
        // Slight delay so the banner doesn't fight the page mount
        const id = setTimeout(() => setVisible(true), 700);
        return () => clearTimeout(id);
      }
    } catch (e) { /* private mode: just show it */ setVisible(true); }
  }, []);

  const dismiss = (mode) => {
    try { localStorage.setItem('kinesuite-cookies', mode); } catch {}
    setVisible(false);
  };

  const openPrivacy = () => {
    dismiss('acknowledged');
    const lang = document.documentElement.getAttribute('lang') || 'es';
    const path = lang === 'en' ? 'legal/privacy.html' : 'legal/privacidad.html';
    window.open(path, '_blank', 'noopener,noreferrer');
  };

  if (!visible) return null;

  return (
    <div style={{
      position: 'fixed',
      bottom: 20, left: 20,
      maxWidth: 380, width: 'calc(100% - 40px)',
      background: 'var(--paper)',
      border: '1px solid var(--gray-200)',
      borderRadius: 16,
      padding: 20,
      boxShadow: '0 18px 40px rgba(15, 25, 50, 0.18), 0 2px 0 rgba(0,0,0,0.04)',
      zIndex: 50,
      fontFamily: 'var(--font-sans)',
      display: 'flex', flexDirection: 'column', gap: 12,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 28, height: 28, borderRadius: 8,
          background: 'var(--primary-100)', color: 'var(--primary)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5z" />
            <circle cx="9" cy="10" r="0.5" fill="currentColor" /><circle cx="14" cy="13" r="0.5" fill="currentColor" />
            <circle cx="11" cy="16" r="0.5" fill="currentColor" />
          </svg>
        </div>
        <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)', letterSpacing: '-0.015em' }}>
          {t.cookieTitle}
        </div>
      </div>
      <p style={{ fontSize: 13.5, lineHeight: 1.5, color: 'var(--gray-700)', margin: 0 }}>
        {t.cookieBody}
      </p>
      {details && (
        <ul style={{
          listStyle: 'none', padding: 0, margin: 0,
          display: 'flex', flexDirection: 'column', gap: 6,
          fontSize: 12.5, color: 'var(--gray-500)',
          background: 'var(--gray-050)',
          padding: 12, borderRadius: 10,
        }}>
          {t.cookieDetails.map((d, i) => (
            <li key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
              <span style={{ color: 'var(--gray-700)' }}>{d.t}</span>
              <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10.5, letterSpacing: '0.06em', color: d.required ? 'var(--ink)' : 'var(--gray-500)' }}>
                {d.required ? t.cookieRequired : t.cookieOptional}
              </span>
            </li>
          ))}
        </ul>
      )}
      <div style={{ display: 'flex', gap: 8, marginTop: 4, alignItems: 'center' }}>
        <button
          onClick={() => dismiss('acknowledged')}
          className="btn btn-primary"
          style={{ flex: 1, justifyContent: 'center', fontSize: 13, padding: '10px 14px' }}
        >
          {t.cookieAccept}
        </button>
        <button
          onClick={openPrivacy}
          className="btn btn-ghost"
          style={{ fontSize: 13, padding: '10px 14px' }}
        >
          {t.cookieEssential}
        </button>
      </div>
      <button
        onClick={() => setDetails((v) => !v)}
        style={{
          background: 'transparent', border: 'none', padding: 0, cursor: 'pointer',
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase',
          color: 'var(--gray-500)', textAlign: 'left', fontWeight: 600,
          marginTop: -2,
        }}
      >
        {details ? t.cookieHide : t.cookieDetailsToggle}
      </button>
    </div>
  );
}

Object.assign(window, {
  HeroPhoneStack, HeroMockDisclaimer,
  AnimatedHeroPhone, ClinicsSection, ChangelogSection, CookieBanner,
});
