/* global React */
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;

// ============================================================
// HERO — editorial, single column, rotating serif-italic verb
// ============================================================
function Hero({ t, accentVar, onCta, onSecondary }) {
  const [rotIndex, setRotIndex] = useStateH(0);
  const [typed, setTyped] = useStateH('');
  const [phase, setPhase] = useStateH('typing'); // typing | holding | deleting
  const rotators = t.hero.rotators;

  useEffectH(() => {
    const current = rotators[rotIndex];
    let timer;
    if (phase === 'typing') {
      if (typed.length < current.length) {
        timer = setTimeout(() => setTyped(current.slice(0, typed.length + 1)), 70);
      } else {
        timer = setTimeout(() => setPhase('holding'), 1800);
      }
    } else if (phase === 'holding') {
      timer = setTimeout(() => setPhase('deleting'), 0);
    } else {
      if (typed.length > 0) {
        timer = setTimeout(() => setTyped(current.slice(0, typed.length - 1)), 40);
      } else {
        setRotIndex((rotIndex + 1) % rotators.length);
        setPhase('typing');
      }
    }
    return () => clearTimeout(timer);
  }, [typed, phase, rotIndex, rotators]);

  // reset when language changes
  useEffectH(() => {
    setTyped('');
    setPhase('typing');
    setRotIndex(0);
  }, [rotators.join('|')]);

  return (
    <section id="top" style={heroStyles.root}>
      <div style={heroStyles.metaTop}>
        <span style={heroStyles.metaMono}>{t.hero.metaLeft}</span>
        <span style={heroStyles.metaMono}>{t.hero.metaRight}</span>
      </div>

      <div style={heroStyles.inner}>
        <div style={heroStyles.eyebrow}>{t.hero.eyebrow}</div>

        <h1 style={heroStyles.h1}>
          <span style={heroStyles.line}>{t.hero.titleA}</span>
          <span style={heroStyles.lineRow}>
            <span>{t.hero.titleB}&nbsp;</span>
            <em style={{ ...heroStyles.em, color: accentVar }}>
              {typed}
              <span style={heroStyles.caret} />
            </em>
          </span>
        </h1>

        <p style={heroStyles.lede}>{t.hero.lede}</p>

        <div style={heroStyles.ctas}>
          <button onClick={onCta} style={{ ...heroStyles.primary, background: 'var(--fg-strong)' }}>
            {t.hero.ctaPrimary}
          </button>
          <button onClick={onSecondary} style={heroStyles.ghost}>
            {t.hero.ctaSecondary}
          </button>
        </div>
      </div>

      {/* Signature: four unit tags floating in the bottom */}
      <div style={heroStyles.unitStrip}>
        {UNIT_KEYS.map(k => (
          <span key={k} className={`u-tag u-tag--${k}`} style={{ fontSize: 13, padding: '4px 8px' }}>
            {CONTENT.en.unitData[k].tag}
          </span>
        ))}
      </div>
    </section>
  );
}

const heroStyles = {
  root: { padding: '40px 40px 100px', position: 'relative' },
  metaTop: {
    display: 'flex', justifyContent: 'space-between',
    fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-subtle)',
    padding: '0 8px 40px', borderBottom: '1px solid var(--border)', marginBottom: 80,
  },
  metaMono: { letterSpacing: '0.02em' },
  inner: { maxWidth: 1080, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 28 },
  eyebrow: { fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 500, color: 'var(--fg-muted)' },
  h1: {
    fontFamily: 'var(--font-sans)', fontSize: 'clamp(56px, 9vw, 120px)',
    fontWeight: 500, lineHeight: 0.98, letterSpacing: '-0.04em',
    color: 'var(--fg-strong)', margin: 0,
  },
  line: { display: 'block' },
  lineRow: { display: 'flex', alignItems: 'baseline', flexWrap: 'wrap' },
  em: {
    fontFamily: 'var(--font-serif)', fontStyle: 'italic',
    fontWeight: 400, letterSpacing: '-0.02em',
    display: 'inline-flex', alignItems: 'baseline',
  },
  caret: {
    display: 'inline-block', width: 3, height: '0.85em',
    background: 'currentColor', marginLeft: 4,
    animation: 'blink 1s step-end infinite',
    verticalAlign: 'baseline',
  },
  lede: {
    fontSize: 20, lineHeight: 1.5, color: 'var(--fg-muted)',
    maxWidth: 640, margin: '12px 0 0', fontWeight: 400,
  },
  ctas: { display: 'flex', gap: 12, marginTop: 20, flexWrap: 'wrap' },
  primary: {
    color: '#fff', border: 'none', padding: '14px 22px',
    borderRadius: 6, fontSize: 14, fontWeight: 500, cursor: 'pointer',
    fontFamily: 'var(--font-sans)',
  },
  ghost: {
    background: 'transparent', color: 'var(--fg-strong)',
    border: '1px solid var(--border-strong)',
    padding: '14px 18px', borderRadius: 6, fontSize: 14,
    fontWeight: 500, cursor: 'pointer', fontFamily: 'var(--font-sans)',
  },
  unitStrip: {
    maxWidth: 1080, margin: '64px auto 0',
    display: 'flex', gap: 8, alignItems: 'center',
    paddingTop: 28, borderTop: '1px solid var(--border)',
  },
};

// ============================================================
// METRICS STRIP — four numbers, horizontal rail
// ============================================================
function Metrics({ t }) {
  const names = (typeof window !== 'undefined' && window.CLIENT_LOGOS) || [];
  const loop = [...names, ...names];
  return (
    <section style={metricStyles.root}>
      <div style={metricStyles.wrap}>
        <div style={metricStyles.fadeL} />
        <div style={metricStyles.fadeR} />
        <div className="clientMarquee" style={metricStyles.track}>
          {loop.map((n, i) => (
            <div key={i} style={metricStyles.cell}>
              <span style={metricStyles.name}>{n}</span>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @keyframes clientMarquee {
          0% { transform: translateX(0); }
          100% { transform: translateX(-50%); }
        }
        .clientMarquee { animation: clientMarquee 60s linear infinite; }
        .clientMarquee:hover { animation-play-state: paused; }
      `}</style>
    </section>
  );
}

const metricStyles = {
  root: { padding: '0 0 100px' },
  wrap: {
    position: 'relative', overflow: 'hidden',
    borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)',
  },
  fadeL: {
    position: 'absolute', left: 0, top: 0, bottom: 0, width: 120, zIndex: 2,
    background: 'linear-gradient(to right, var(--bg), transparent)', pointerEvents: 'none',
  },
  fadeR: {
    position: 'absolute', right: 0, top: 0, bottom: 0, width: 120, zIndex: 2,
    background: 'linear-gradient(to left, var(--bg), transparent)', pointerEvents: 'none',
  },
  track: {
    display: 'flex', width: 'max-content', willChange: 'transform',
  },
  cell: {
    flex: '0 0 auto', padding: '36px 44px',
    borderRight: '1px solid var(--border)',
    display: 'flex', alignItems: 'center',
  },
  name: {
    fontFamily: 'var(--font-sans)', fontSize: 24, fontWeight: 500,
    letterSpacing: '-0.02em', color: 'var(--fg-strong)', lineHeight: 1,
    whiteSpace: 'nowrap',
  },
};

// ============================================================
// UNITS — 4 cards with accent tag + active-unit visual link
// ============================================================
function Units({ t, activeUnit, setActiveUnit }) {
  return (
    <section id="units" style={unitsStyles.root}>
      <div style={unitsStyles.inner}>
        <div style={unitsStyles.head}>
          <div style={unitsStyles.eyebrow}>{t.units.eyebrow}</div>
          <h2 style={unitsStyles.h2}>
            {t.units.title}<br/>
            <em style={unitsStyles.em}>{t.units.titleEm}</em>
          </h2>
          <p style={unitsStyles.lede}>{t.units.lede}</p>
          <div style={unitsStyles.switchHint}>{t.units.switcher}</div>
        </div>

        <div style={unitsStyles.grid}>
          {UNIT_KEYS.map(k => {
            const u = t.unitData[k];
            const active = activeUnit === k;
            const col = `var(--${k}-500)`;
            const colBg = `var(--${k}-100)`;
            return (
              <article
                key={k}
                onClick={() => setActiveUnit(k)}
                style={{
                  ...unitsStyles.card,
                  borderColor: active ? col : 'var(--border)',
                  boxShadow: active ? `0 0 0 2px ${col} inset, 0 16px 40px rgba(10,9,7,0.06)` : 'none',
                }}
              >
                <div style={{ ...unitsStyles.bar, background: col }}/>
                <div style={unitsStyles.body}>
                  <div style={unitsStyles.rowTop}>
                    <span className={`u-tag u-tag--${k}`} style={{ fontSize: 12, padding: '3px 7px' }}>{u.tag}</span>
                    <span style={{ ...unitsStyles.forLabel, color: 'var(--fg-subtle)' }}>{u.for}</span>
                  </div>
                  <h3 style={unitsStyles.name}>{u.name}</h3>
                  <div style={{ ...unitsStyles.tagline, color: col }}>{u.tagline}</div>
                  <p style={unitsStyles.desc}>{u.body}</p>
                  <ul style={unitsStyles.bullets}>
                    {u.bullets.map((b, i) => (
                      <li key={i} style={unitsStyles.bullet}>
                        <span style={{ ...unitsStyles.dash, color: col }}>→</span>
                        <span>{b}</span>
                      </li>
                    ))}
                  </ul>
                  <a
                    href={k === 'labs' ? 'prodct Labs.html' : k === 'cx' ? 'prodct CX.html' : k === 'elements' ? 'prodct Elements.html' : k === 'skills' ? 'prodct Skills.html' : '#'}
                    style={{ ...unitsStyles.link, color: col, background: colBg }}
                  >
                    {u.link}  →
                  </a>
                </div>
              </article>
            );
          })}
        </div>
      </div>
    </section>
  );
}

const unitsStyles = {
  root: { padding: '20px 40px 120px' },
  inner: { maxWidth: 1200, margin: '0 auto' },
  head: { display: 'flex', flexDirection: 'column', gap: 16, marginBottom: 56, maxWidth: 720 },
  eyebrow: { fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-muted)' },
  h2: {
    fontFamily: 'var(--font-sans)', fontSize: 'clamp(40px, 5.5vw, 68px)',
    fontWeight: 500, letterSpacing: '-0.035em', lineHeight: 1.02,
    color: 'var(--fg-strong)', margin: 0,
  },
  em: {
    fontFamily: 'var(--font-serif)', fontStyle: 'italic',
    fontWeight: 400, color: 'var(--prodct-500)',
  },
  lede: { fontSize: 17, lineHeight: 1.55, color: 'var(--fg-muted)', margin: '4px 0 0', maxWidth: 580 },
  switchHint: {
    fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-subtle)',
    marginTop: 8,
  },
  grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(420px, 1fr))', gap: 20 },
  card: {
    background: 'var(--bg-elevated)', border: '1px solid var(--border)',
    borderRadius: 10, overflow: 'hidden', display: 'flex', flexDirection: 'column',
    cursor: 'pointer', transition: 'border-color 220ms var(--ease-out), box-shadow 220ms var(--ease-out)',
  },
  bar: { height: 3 },
  body: { padding: '28px 28px 28px', display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'flex-start' },
  rowTop: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', gap: 12 },
  forLabel: { fontFamily: 'var(--font-mono)', fontSize: 11, textAlign: 'right' },
  name: {
    fontFamily: 'var(--font-sans)', fontSize: 28, fontWeight: 500,
    color: 'var(--fg-strong)', margin: '2px 0 0', letterSpacing: '-0.025em',
  },
  tagline: { fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 20, lineHeight: 1.2, margin: '-4px 0 4px' },
  desc: { fontSize: 14.5, lineHeight: 1.6, color: 'var(--fg-muted)', margin: 0 },
  bullets: { listStyle: 'none', padding: 0, margin: '6px 0 10px', display: 'flex', flexDirection: 'column', gap: 8, width: '100%' },
  bullet: { display: 'flex', gap: 10, fontSize: 13.5, color: 'var(--fg)', lineHeight: 1.5 },
  dash: { fontFamily: 'var(--font-mono)', flexShrink: 0 },
  link: {
    fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 500,
    padding: '8px 14px', borderRadius: 6, textDecoration: 'none',
    marginTop: 4,
  },
};

Object.assign(window, { Hero, Metrics, Units });
