
const LETTERS = ['T', 'I', 'D', 'E', 'S'];

const Wordmark = ({ tweaks }) => {
  const [wetness, setWetness] = React.useState([0, 0, 0, 0, 0]); // 0..1 per letter
  const [bob, setBob] = React.useState([0, 0, 0, 0, 0]);
  const [rot, setRot] = React.useState([0, 0, 0, 0, 0]);
  const wrapRef = React.useRef(null);
  const wetnessRef = React.useRef([0, 0, 0, 0, 0]);
  // physics state per letter — spring toward target with velocity overshoot
  const physRef = React.useRef(
    Array.from({ length: LETTERS.length }, () => ({ y: 0, vy: 0, r: 0, vr: 0 }))
  );
  const lastTimeRef = React.useRef(performance.now());

  React.useEffect(() => {
    let raf;
    const loop = (now) => {
      if (!wrapRef.current || !window.__tides) { raf = requestAnimationFrame(loop); return; }
      const dt = Math.min(0.033, (now - lastTimeRef.current) / 1000);
      lastTimeRef.current = now;

      const letterEls = wrapRef.current.querySelectorAll('[data-letter]');
      const newBob = [];
      const newRot = [];
      const newWet = [...wetnessRef.current];
      const phys = physRef.current;

      // Spring params — underdamped so letters overshoot & bounce when water shoves them up.
      const k = 110;    // stiffness
      const d = 5.2;    // damping (low => bouncy)
      const kR = 60;    // rotational stiffness
      const dR = 3.0;

      letterEls.forEach((el, i) => {
        const r = el.getBoundingClientRect();
        const cx = r.left + r.width / 2;
        const bottomY = r.bottom;
        // sample water at letter center AND at edges for a tilt cue
        const surfaceMid = window.__tides.surfaceY(cx);
        const surfaceL   = window.__tides.surfaceY(r.left  + r.width * 0.25);
        const surfaceR   = window.__tides.surfaceY(r.right - r.width * 0.25);

        // submersion in pixels — how far the water is above the letter's bottom
        const submersion = Math.max(0, bottomY - surfaceMid);

        // Buoyancy target: stronger push the deeper it is; saturates so it doesn't fly off.
        // Each letter gets a tiny phase offset so they don't bounce in perfect sync.
        const phase = i * 0.7;
        const buoyWobble = 1 + 0.08 * Math.sin(window.__tides.state.t * 3 + phase);
        const target = -Math.min(48, submersion * 0.7) * buoyWobble;

        // Spring integration
        const p = phys[i];
        const ay = k * (target - p.y) - d * p.vy;
        p.vy += ay * dt;
        p.y  += p.vy * dt;

        // Rotation: tilt based on L/R water difference when submerged; else spring back to 0.
        const tilt = submersion > 0
          ? (surfaceR - surfaceL) * 0.06    // radians-ish scale (we use deg below)
          : 0;
        const targetR = tilt;
        const ar = kR * (targetR - p.r) - dR * p.vr;
        p.vr += ar * dt;
        p.r  += p.vr * dt;

        newBob.push(p.y);
        newRot.push(p.r);

        // wetness — still the color/wet-sand effect
        if (surfaceMid < bottomY) {
          newWet[i] = Math.min(1, newWet[i] + 0.08);
        } else {
          newWet[i] = Math.max(0, newWet[i] - 0.004);
        }
      });

      wetnessRef.current = newWet;
      setBob(newBob);
      setRot(newRot);
      setWetness([...newWet]);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Each letter gets a tiny rotation baseline so they feel hand-set, not lockstep.
  const letterJitter = [ -1.2, 0.6, -0.4, 0.9, -0.7 ];

  const fontStack = (tweaks && tweaks.wordmarkFont) === 'cormorant'
    ? "'Cormorant Garamond', serif"
    : (tweaks && tweaks.wordmarkFont) === 'fraunces'
      ? "'Fraunces', serif"
      : "'Instrument Serif', serif";
  const italic = !!(tweaks && tweaks.wordmarkItalic);

  return (
    <div
      ref={wrapRef}
      style={{
        fontFamily: fontStack,
        fontStyle: italic ? 'italic' : 'normal',
        fontWeight: 400,
        fontSize: 'clamp(100px, 20vw, 320px)',
        lineHeight: 0.88,
        letterSpacing: '-0.01em',
        color: 'var(--ink)',
        userSelect: 'none',
        display: 'flex',
        gap: '0.01em',
      }}
    >
      {LETTERS.map((L, i) => (
        <span
          key={i}
          data-letter={L}
          style={{
            display: 'inline-block',
            transformOrigin: '50% 90%',
            transform: `translateY(${bob[i] || 0}px) rotate(${((rot[i] || 0) * 8) + letterJitter[i]}deg)`,
            transition: 'color 0.4s ease',
            color: wetness[i] > 0.01
              ? `color-mix(in oklab, var(--ink) ${100 - wetness[i]*30}%, var(--wet) ${wetness[i]*30}%)`
              : 'var(--ink)',
            textShadow: wetness[i] > 0.1
              ? `0 0 ${wetness[i]*30}px rgba(14,37,48,${wetness[i]*0.35})`
              : 'none',
            willChange: 'transform',
          }}
        >
          {L}
        </span>
      ))}
    </div>
  );
};

window.Wordmark = Wordmark;
