// Hi-fi V3: annotated full-bleed — responsive (mobile + desktop)

const { EmailSVG: HiFiEmail } = window;

function useWindowWidth() {
  const [w, setW] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const fn = () => setW(window.innerWidth);
    window.addEventListener('resize', fn);
    return () => window.removeEventListener('resize', fn);
  }, []);
  return w;
}

// ─── Icons ────────────────────────────────────────────────────────────────────

function RefinedGear({ stroke, sw = 1.5 }) {
  const teeth = [];
  for (let i = 0; i < 10; i++) {
    const a = (i * Math.PI * 2) / 10 - Math.PI / 2;
    const x1 = 50 + Math.cos(a) * 30;
    const y1 = 50 + Math.sin(a) * 30;
    const x2 = 50 + Math.cos(a) * 40;
    const y2 = 50 + Math.sin(a) * 40;
    teeth.push(<line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={stroke} strokeWidth={sw + 1.5} strokeLinecap="round" />);
  }
  return (
    <g fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round">
      <circle cx="50" cy="50" r="30" />
      <circle cx="50" cy="50" r="9" />
      {teeth}
    </g>
  );
}

function RefinedCamera({ stroke, sw = 1.5 }) {
  return (
    <g fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 38 L28 38 L33 28 L67 28 L72 38 L86 38 L86 76 L14 76 Z" />
      <circle cx="50" cy="55" r="16" />
      <circle cx="50" cy="55" r="11" />
      <circle cx="50" cy="55" r="5" />
      <rect x="44" y="22" width="12" height="6" rx="1" />
      <circle cx="78" cy="44" r="2.5" />
      <circle cx="22" cy="44" r="1.8" fill={stroke} stroke="none" />
    </g>
  );
}

function RefinedCode({ stroke, sw = 1.8 }) {
  return (
    <g fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <path d="M32 26 L12 50 L32 74" />
      <path d="M68 26 L88 50 L68 74" />
      <line x1="60" y1="22" x2="40" y2="78" />
    </g>
  );
}

const REFINED_ICONS = ['gear', 'camera', 'code'];
const REFINED_LABELS = { gear: 'engineering', camera: 'photography', code: 'coding' };

function RefinedShape({ name, stroke, sw }) {
  if (name === 'gear') return <RefinedGear stroke={stroke} sw={sw} />;
  if (name === 'camera') return <RefinedCamera stroke={stroke} sw={sw} />;
  if (name === 'code') return <RefinedCode stroke={stroke} sw={sw} />;
  return null;
}

// ─── Morph animation ──────────────────────────────────────────────────────────

function RefinedMorph({ size = 360, style = 'crossfade', speed = 1, accent = 'currentColor' }) {
  const [active, setActive] = React.useState(0);
  const [phase, setPhase] = React.useState('in');

  React.useEffect(() => {
    const HOLD = 1800 / speed;
    const TRANS = 700 / speed;
    let timer;
    const cycle = () => {
      setPhase('in');
      timer = setTimeout(() => {
        setPhase('hold');
        timer = setTimeout(() => {
          setPhase('out');
          timer = setTimeout(() => {
            setActive((a) => (a + 1) % REFINED_ICONS.length);
          }, TRANS);
        }, HOLD);
      }, TRANS);
    };
    cycle();
    return () => clearTimeout(timer);
  }, [active, speed]);

  const name = REFINED_ICONS[active];
  let transform = 'none';
  let opacity = 1;

  if (style === 'crossfade') {
    if (phase === 'in')   { transform = 'scale(0.92) rotate(-4deg)'; opacity = 0; }
    if (phase === 'hold') { transform = 'scale(1) rotate(0deg)';     opacity = 1; }
    if (phase === 'out')  { transform = 'scale(1.08) rotate(4deg)';  opacity = 0; }
  } else if (style === 'redraw') {
    transform = 'none';
    opacity = phase === 'out' ? 0 : 1;
  } else if (style === 'spin') {
    if (phase === 'in')   { transform = 'rotate(-180deg) scale(0.5)'; opacity = 0; }
    if (phase === 'hold') { transform = 'rotate(0deg) scale(1)';      opacity = 1; }
    if (phase === 'out')  { transform = 'rotate(180deg) scale(0.5)';  opacity = 0; }
  } else if (style === 'slide') {
    if (phase === 'in')   { transform = 'translateY(24px)'; opacity = 0; }
    if (phase === 'hold') { transform = 'translateY(0)';    opacity = 1; }
    if (phase === 'out')  { transform = 'translateY(-24px)'; opacity = 0; }
  }

  const transitionMs = (style === 'redraw' ? 900 : 600) / speed;

  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg
        viewBox="0 0 100 100"
        width={size}
        height={size}
        style={{
          transform,
          opacity,
          transition: `transform ${transitionMs}ms cubic-bezier(.5,.1,.3,1.2), opacity ${transitionMs}ms ease`,
          color: accent,
          overflow: 'visible',
        }}
      >
        {style === 'redraw' ? (
          <g
            key={`${name}-${active}`}
            style={{
              strokeDasharray: 240,
              strokeDashoffset: phase === 'in' ? 240 : 0,
              transition: `stroke-dashoffset ${transitionMs}ms ease`,
            }}
          >
            <RefinedShape name={name} stroke={accent} sw={1.6} />
          </g>
        ) : (
          <RefinedShape name={name} stroke={accent} sw={1.6} />
        )}
      </svg>
      <div style={{
        position: 'absolute',
        bottom: -32,
        left: '50%',
        transform: 'translateX(-50%)',
        fontFamily: 'JetBrains Mono, ui-monospace, monospace',
        fontSize: 11,
        letterSpacing: '0.25em',
        textTransform: 'uppercase',
        color: 'var(--ink-soft)',
        opacity: phase === 'hold' ? 1 : 0,
        transition: 'opacity 300ms',
        whiteSpace: 'nowrap',
      }}>
        — {REFINED_LABELS[name]} —
      </div>
    </div>
  );
}

// ─── Shared pieces ────────────────────────────────────────────────────────────

function PortraitPlaceholder({ accent }) {
  return (
    <div style={{
      width: 56, height: 56, borderRadius: '50%',
      border: '1px solid var(--ink-soft)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'Instrument Serif, Georgia, serif',
      fontSize: 24, color: 'var(--ink)',
      background: 'var(--paper-tint)',
      position: 'relative', flexShrink: 0,
    }}>
      CP
      <div style={{
        position: 'absolute', bottom: -2, right: -2,
        width: 12, height: 12, borderRadius: '50%',
        background: accent, border: '2px solid var(--paper)',
      }} />
    </div>
  );
}

function LinkedInLinkHF({ accent }) {
  return (
    <a
      href="https://www.linkedin.com/in/christophphilippch/"
      target="_blank"
      rel="noopener"
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        textDecoration: 'none', color: 'var(--ink)',
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
        borderBottom: `1px solid ${accent}`, paddingBottom: 2,
      }}
    >
      <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor">
        <path d="M20.5 2h-17A1.5 1.5 0 002 3.5v17A1.5 1.5 0 003.5 22h17a1.5 1.5 0 001.5-1.5v-17A1.5 1.5 0 0020.5 2zM8 19H5v-9h3zM6.5 8.25A1.75 1.75 0 118.3 6.5a1.78 1.78 0 01-1.8 1.75zM19 19h-3v-4.74c0-1.42-.6-1.93-1.38-1.93A1.74 1.74 0 0013 14.19a.66.66 0 000 .14V19h-3v-9h2.9v1.3a3.11 3.11 0 012.7-1.4c1.55 0 3.36.86 3.36 3.66z"/>
      </svg>
      LinkedIn ↗
    </a>
  );
}

function GridBGHF() {
  return (
    <div
      aria-hidden
      style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        backgroundImage: `
          linear-gradient(to right, rgba(0,0,0,0.035) 1px, transparent 1px),
          linear-gradient(to bottom, rgba(0,0,0,0.035) 1px, transparent 1px)
        `,
        backgroundSize: '40px 40px',
      }}
    />
  );
}

function RegisterMark({ style }) {
  return (
    <div aria-hidden style={{ position: 'absolute', width: 16, height: 16, color: 'var(--ink-soft)', ...style }}>
      <svg viewBox="0 0 16 16" width="16" height="16">
        <line x1="8" y1="0" x2="8" y2="16" stroke="currentColor" strokeWidth="0.5" />
        <line x1="0" y1="8" x2="16" y2="8" stroke="currentColor" strokeWidth="0.5" />
        <circle cx="8" cy="8" r="3" fill="none" stroke="currentColor" strokeWidth="0.5" />
      </svg>
    </div>
  );
}

const mono = 'JetBrains Mono, ui-monospace, monospace';
const serif = 'Instrument Serif, Georgia, serif';
const label = { fontFamily: mono, fontSize: 9, letterSpacing: '0.25em', textTransform: 'uppercase', color: 'var(--ink-soft)' };

// ─── Mobile layout ────────────────────────────────────────────────────────────

function MobileLayout({ animationStyle, accent, speed }) {
  return (
    <div style={{
      minHeight: '100vh',
      background: 'var(--paper)',
      color: 'var(--ink)',
      fontFamily: 'Inter, system-ui, sans-serif',
      position: 'relative',
      overflowX: 'hidden',
    }}>
      <GridBGHF />
      <div style={{ position: 'relative', padding: '48px 28px 40px' }}>

        {/* Identity row */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 28 }}>
          <PortraitPlaceholder accent={accent} />
          <div>
            <div style={{ ...label, marginBottom: 4 }}>hello, I'm</div>
            <div style={{ ...label, display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: accent }} />
              Switzerland · CH
            </div>
          </div>
        </div>

        {/* Name */}
        <h1 style={{
          fontFamily: serif, fontSize: 'clamp(56px, 15vw, 80px)',
          fontWeight: 400, margin: '0 0 40px', lineHeight: 0.92, letterSpacing: '-0.015em',
        }}>
          Christoph<br />
          <span style={{ fontStyle: 'italic', color: accent }}>Philipp</span>
        </h1>

        {/* Morph icon */}
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 56 }}>
          <RefinedMorph size={180} style={animationStyle} accent={accent} speed={speed} />
        </div>

        {/* Roles */}
        <div style={{ marginBottom: 36 }}>
          <div style={{ ...label, marginBottom: 12 }}>✶ what I am</div>
          <div style={{ fontFamily: serif, fontSize: 22, lineHeight: 1.5 }}>
            problem solver,<br />
            technology geek,<br />
            <span style={{ fontStyle: 'italic' }}>creative,</span><br />
            family father.
          </div>
        </div>

        {/* About */}
        <div style={{ marginBottom: 28 }}>
          <div style={{ ...label, marginBottom: 10 }}>↘ about</div>
          <p style={{ fontFamily: serif, fontSize: 17, lineHeight: 1.5, margin: 0 }}>
            Knowledge that extends into <span style={{ color: accent, fontStyle: 'italic' }}>mechanics</span>, electronics, software, IT, and agile development tools.
          </p>
        </div>

        {/* Off-hours */}
        <div style={{ marginBottom: 48 }}>
          <div style={{ ...label, marginBottom: 10 }}>off-hours</div>
          <p style={{ fontFamily: serif, fontSize: 17, lineHeight: 1.5, margin: 0 }}>
            Sports, <span style={{ color: accent, fontStyle: 'italic' }}>photography</span>, knowledge, coding — the loop keeps spinning.
          </p>
        </div>

        {/* Contact */}
        <div style={{ borderTop: '1px solid var(--ink-soft)', paddingTop: 24, display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div>
            <div style={{ ...label, marginBottom: 8 }}>✦ get in touch</div>
            <HiFiEmail width={220} color="var(--ink)" font={mono} size={14} />
          </div>
          <div>
            <div style={{ ...label, marginBottom: 8 }}>✦ elsewhere</div>
            <LinkedInLinkHF accent={accent} />
          </div>
        </div>

        {/* Year */}
        <div style={{ ...label, fontSize: 8, opacity: 0.5, textAlign: 'center', marginTop: 32 }}>
          © 2026
        </div>
      </div>
    </div>
  );
}

// ─── Desktop layout (scaled to fit viewport) ──────────────────────────────────

function DesktopLayout({ animationStyle, accent, speed, viewportWidth }) {
  const scale = Math.min(1, viewportWidth / 1200);
  const scaledHeight = Math.round(800 * scale);

  return (
    <div style={{ width: '100vw', height: scaledHeight, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{
        width: 1200, height: 800,
        transform: `scale(${scale})`,
        transformOrigin: 'center center',
        position: 'relative',
        background: 'var(--paper)',
        color: 'var(--ink)',
        overflow: 'hidden',
        fontFamily: 'Inter, system-ui, sans-serif',
        flexShrink: 0,
      }}>
        <GridBGHF />

        <RegisterMark style={{ top: 24, left: 24 }} />
        <RegisterMark style={{ top: 24, right: 24 }} />
        <RegisterMark style={{ bottom: 24, left: 24 }} />
        <RegisterMark style={{ bottom: 24, right: 24 }} />

        {/* center: huge morph */}
        <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -54%)' }}>
          <RefinedMorph size={420} style={animationStyle} accent={accent} speed={speed} />
        </div>

        {/* TOP-LEFT: identity */}
        <div style={{ position: 'absolute', top: 60, left: 64, maxWidth: 320 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 22 }}>
            <PortraitPlaceholder accent={accent} />
            <div>
              <div style={{ ...label, marginBottom: 4 }}>hello, I'm</div>
              <div style={{ ...label, display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: accent }} />
                Switzerland · CH
              </div>
            </div>
          </div>
          <h1 style={{
            fontFamily: serif, fontSize: 84, fontWeight: 400,
            margin: 0, lineHeight: 0.92, letterSpacing: '-0.015em',
          }}>
            Christoph<br />
            <span style={{ fontStyle: 'italic', color: accent }}>Philipp</span>
          </h1>
        </div>

        {/* TOP-RIGHT: roles */}
        <div style={{ position: 'absolute', top: 80, right: 64, textAlign: 'right' }}>
          <div style={{ ...label, marginBottom: 14 }}>✶ what I am</div>
          <div style={{ fontFamily: serif, fontSize: 22, lineHeight: 1.5 }}>
            problem solver,<br />
            technology geek,<br />
            <span style={{ fontStyle: 'italic' }}>creative,</span><br />
            family father.
          </div>
        </div>

        {/* MID-LEFT: about */}
        <div style={{ position: 'absolute', bottom: 200, left: 64, maxWidth: 280 }}>
          <div style={{ ...label, marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>↘ about</span>
            <span style={{ flex: 1, height: 1, background: 'currentColor', opacity: 0.4 }} />
          </div>
          <p style={{ fontFamily: serif, fontSize: 17, lineHeight: 1.45, margin: 0 }}>
            Knowledge that extends into <span style={{ color: accent, fontStyle: 'italic' }}>mechanics</span>, electronics, software, IT, and agile development tools.
          </p>
        </div>

        {/* MID-RIGHT: off-hours */}
        <div style={{ position: 'absolute', bottom: 200, right: 64, maxWidth: 260, textAlign: 'right' }}>
          <div style={{ ...label, marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}>
            <span style={{ flex: 1, height: 1, background: 'currentColor', opacity: 0.4 }} />
            <span>off-hours ↙</span>
          </div>
          <p style={{ fontFamily: serif, fontSize: 17, lineHeight: 1.45, margin: 0 }}>
            Sports, <span style={{ color: accent, fontStyle: 'italic' }}>photography</span>, knowledge, coding — the loop keeps spinning.
          </p>
        </div>

        {/* BOTTOM: contact bar */}
        <div style={{
          position: 'absolute', bottom: 56, left: 64, right: 64,
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
          paddingTop: 24, borderTop: '1px solid var(--ink-soft)',
        }}>
          <div>
            <div style={{ ...label, marginBottom: 8 }}>✦ get in touch</div>
            <HiFiEmail width={260} color="var(--ink)" font={mono} size={15} />
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
            <div style={label}>✦ elsewhere</div>
            <LinkedInLinkHF accent={accent} />
          </div>
        </div>

        {/* year */}
        <div style={{ position: 'absolute', bottom: 22, left: '50%', transform: 'translateX(-50%)', ...label, fontSize: 8, opacity: 0.5 }}>
          © 2026
        </div>
      </div>
    </div>
  );
}

// ─── Main export ──────────────────────────────────────────────────────────────

function HiFiV3({ animationStyle, accent, speed }) {
  const w = useWindowWidth();
  if (w < 768) {
    return <MobileLayout animationStyle={animationStyle} accent={accent} speed={speed} />;
  }
  return <DesktopLayout animationStyle={animationStyle} accent={accent} speed={speed} viewportWidth={w} />;
}

window.HiFiV3 = HiFiV3;
