
// Contact section + Lanyard Discord widget (WebSocket)

const LANYARD_USER_ID = "832751255248044093";
const LANYARD_WS = "wss://api.lanyard.rest/socket";
const OPC = { EVENT: 0, HELLO: 1, INITIALIZE: 2, HEARTBEAT: 3 };

function useLanyard(userId) {
  const [data, setData] = React.useState(null);
  const [wsStatus, setWsStatus] = React.useState("connecting");
  const wsRef = React.useRef(null);
  const hbRef = React.useRef(null);
  const retryRef = React.useRef(null);

  React.useEffect(() => {
    let alive = true;
    const connect = () => {
      if (!alive) return;
      setWsStatus("connecting");
      const ws = new WebSocket(LANYARD_WS);
      wsRef.current = ws;
      ws.onmessage = (e) => {
        const { op, d, t } = JSON.parse(e.data);
        if (op === OPC.HELLO) {
          hbRef.current = setInterval(() => {
            if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ op: OPC.HEARTBEAT }));
          }, d.heartbeat_interval);
          ws.send(JSON.stringify({ op: OPC.INITIALIZE, d: { subscribe_to_id: userId } }));
        }
        if (op === OPC.EVENT && (t === "INIT_STATE" || t === "PRESENCE_UPDATE")) {
          if (alive) { setData(d); setWsStatus("connected"); }
        }
      };
      ws.onerror = () => { if (alive) setWsStatus("error"); };
      ws.onclose = () => {
        clearInterval(hbRef.current);
        if (alive) {
          setWsStatus("disconnected");
          retryRef.current = setTimeout(connect, 5000);
        }
      };
    };
    connect();
    return () => {
      alive = false;
      clearInterval(hbRef.current);
      clearTimeout(retryRef.current);
      if (wsRef.current) wsRef.current.close();
    };
  }, [userId]);

  return { data, wsStatus };
}

function getAvatar(userId, hash, size = 128) {
  if (!hash) {
    const idx = Number(BigInt(userId) >> 22n) % 6;
    return `https://cdn.discordapp.com/embed/avatars/${idx}.png`;
  }
  const ext = hash.startsWith('a_') ? 'gif' : 'webp';
  return `https://cdn.discordapp.com/avatars/${userId}/${hash}.${ext}?size=${size}`;
}

function getActivityAssetUrl(activity) {
  if (!activity?.assets?.large_image) return null;
  const img = activity.assets.large_image;
  if (img.startsWith('mp:external/')) return 'https://media.discordapp.net/external/' + img.slice('mp:external/'.length);
  if (img.startsWith('mp:')) return 'https://media.discordapp.net/' + img.slice('mp:'.length);
  return `https://cdn.discordapp.com/app-assets/${activity.application_id}/${img}.png`;
}

function LiveClock() {
  const [time, setTime] = React.useState('');
  React.useEffect(() => {
    const update = () => setTime(new Date().toLocaleTimeString('fr-BE', { timeZone: 'Europe/Brussels', hour: '2-digit', minute: '2-digit', hour12: false }));
    update();
    const id = setInterval(update, 1000);
    return () => clearInterval(id);
  }, []);
  return <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color: '#444', letterSpacing: '0.1em' }}>{time}</span>;
}

function LanyardWidget() {
  const { data, wsStatus } = useLanyard(LANYARD_USER_ID);

  const status = data?.discord_status || 'offline';
  const user = data?.discord_user;
  const spotify = data?.spotify;
  const activity = data?.activities?.find(a => a.type !== 2 && a.type !== 4);
  const customStatus = data?.activities?.find(a => a.type === 4);
  const avatarUrl = user ? getAvatar(user.id, user.avatar, 128) : null;

  const statusDot = { online: '#23a55a', idle: '#f0b232', dnd: '#f23f43', offline: '#80848e' };
  const statusText = { online: 'Online', idle: 'Idle', dnd: 'Do not disturb', offline: 'Offline' };

  const cardStyle = { border: '1px solid #1a1a1a', background: '#0a0a0a', width: 'clamp(260px, 28vw, 340px)', fontFamily: "'DM Sans', sans-serif", overflow: 'hidden' };
  const monoSm = { fontFamily: "'DM Mono', monospace", fontSize: 8.5, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#2e2e2e' };
  const sectionStyle = { padding: '14px 18px', borderBottom: '1px solid #111' };

  return (
    <div style={cardStyle}>
      {/* Header */}
      <div style={{ padding: '18px 18px 14px', borderBottom: '1px solid #111', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ position: 'relative', flexShrink: 0 }}>
          {avatarUrl
            ? <img src={avatarUrl} alt="" style={{ width: 44, height: 44, borderRadius: '50%', display: 'block', filter: 'grayscale(10%)' }} />
            : <div style={{ width: 44, height: 44, borderRadius: '50%', background: '#111' }} />}
          <div style={{ position: 'absolute', bottom: 1, right: 1, width: 10, height: 10, borderRadius: '50%', background: statusDot[status], border: '2px solid #0a0a0a', boxShadow: status === 'online' ? '0 0 6px rgba(35,165,90,0.4)' : 'none' }} />
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <p style={{ fontFamily: "'Cormorant Garamond', serif", fontWeight: 400, fontSize: 16, color: '#ededeb', lineHeight: 1.1, marginBottom: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {user?.global_name || user?.username || 'muuqi'}
          </p>
          <p style={{ ...monoSm, color: '#333' }}>{wsStatus === 'connected' ? statusText[status] : 'Connecting…'}</p>
          {customStatus?.state && (
            <p style={{ fontFamily: "'DM Sans', sans-serif", fontSize: 11, color: '#2a2a2a', marginTop: 3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {customStatus.emoji?.name ? customStatus.emoji.name + ' ' : ''}{customStatus.state}
            </p>
          )}
        </div>
      </div>

      {/* Location + clock */}
      <div style={{ padding: '10px 18px', borderBottom: '1px solid #0e0e0e', display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{ ...monoSm, color: '#282828' }}>Liège, BE</span>
        <span style={{ ...monoSm, color: '#1e1e1e' }}>·</span>
        <LiveClock />
      </div>

      {/* Spotify */}
      <div style={sectionStyle}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: spotify ? 10 : 0 }}>
          {spotify && (
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 1.5, height: 11 }}>
              {[1,2,3,4].map(i => (
                <div key={i} style={{ width: 2, background: '#3a3a3a', borderRadius: 1, animation: `barPulse ${0.5+i*0.15}s ease-in-out infinite alternate`, height: `${35+i*16}%` }} />
              ))}
            </div>
          )}
          <span style={monoSm}>{spotify ? 'Now playing' : 'Music'}</span>
        </div>
        {spotify ? (
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            {spotify.album_art_url && <img src={spotify.album_art_url} alt="" style={{ width: 38, height: 38, flexShrink: 0, filter: 'grayscale(75%)' }} />}
            <div style={{ minWidth: 0 }}>
              <p style={{ fontSize: 12, color: '#888', fontWeight: 400, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{spotify.song}</p>
              <p style={{ fontSize: 11, color: '#3a3a3a', fontWeight: 300, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 2 }}>{spotify.artist}</p>
            </div>
          </div>
        ) : (
          <p style={{ fontSize: 11, color: '#222' }}>—</p>
        )}
      </div>

      {/* Activity */}
      <div style={sectionStyle}>
        <span style={{ ...monoSm, display: 'block', marginBottom: activity ? 10 : 0 }}>Activity</span>
        {activity ? (
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            {(() => {
              const icon = getActivityAssetUrl(activity);
              return icon
                ? <img src={icon} alt="" style={{ width: 38, height: 38, flexShrink: 0, filter: 'grayscale(70%)' }} />
                : <div style={{ width: 38, height: 38, background: '#111', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><span style={{ fontSize: 16 }}>🎮</span></div>;
            })()}
            <div style={{ minWidth: 0 }}>
              <p style={{ fontSize: 12, color: '#666', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{activity.name}</p>
              {activity.details && <p style={{ fontSize: 11, color: '#333', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 2 }}>{activity.details}</p>}
              {activity.state && <p style={{ fontSize: 11, color: '#2a2a2a', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 1 }}>{activity.state}</p>}
            </div>
          </div>
        ) : (
          <p style={{ fontSize: 11, color: '#222' }}>—</p>
        )}
      </div>

      {/* Add me CTA */}
      <a
        href={`https://discord.com/users/${LANYARD_USER_ID}`}
        target="_blank"
        rel="noopener noreferrer"
        className="discord-add-cta"
        style={{
          display: 'block',
          padding: '14px 18px',
          borderTop: '1px solid #141414',
          textDecoration: 'none',
          position: 'relative',
          overflow: 'hidden',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, position: 'relative', zIndex: 1 }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
              <span style={{ width: 4, height: 4, borderRadius: '50%', background: '#9a9a9a', boxShadow: '0 0 8px rgba(237,237,235,0.35)', animation: 'pulseDot 2s ease-in-out infinite' }} />
              <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 8.5, letterSpacing: '0.24em', textTransform: 'uppercase', color: '#aaa' }}>Add me</span>
            </div>
            <p style={{ fontSize: 12, color: '#ededeb', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 400 }}>
              @{user?.username || 'muuqi'}
            </p>
          </div>
          <span className="discord-add-arrow" style={{ color: '#888', fontSize: 14, lineHeight: 1, transition: 'transform 0.3s ease, color 0.3s ease' }}>↗</span>
        </div>
      </a>
    </div>
  );
}

function DiscordPopup({ onClose }) {
  return (
    <div
      style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
      onClick={onClose}
    >
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)' }} />
      <div
        style={{ position: 'relative', zIndex: 1, animation: 'fadeUp 0.35s cubic-bezier(0.16,1,0.3,1) both' }}
        onClick={e => e.stopPropagation()}
      >
        <button
          onClick={onClose}
          style={{ position: 'absolute', top: 10, right: 10, zIndex: 2, background: 'none', border: '1px solid #1e1e1e', color: '#444', width: 28, height: 28, borderRadius: '50%', fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
        >×</button>
        <LanyardWidget />
      </div>
    </div>
  );
}

function ContactSectionEditorial({ c, t }) {
  const [emailHovered, setEmailHovered] = React.useState(false);
  const [showPopup, setShowPopup] = React.useState(false);
  const { data } = useLanyard(LANYARD_USER_ID);
  const status = data?.discord_status || 'offline';
  const statusDotColor = { online: '#23a55a', idle: '#f0b232', dnd: '#f23f43', offline: '#80848e' };

  const socials = [
    { label: "GitHub", href: "#" },
    { label: "LinkedIn", href: "#" },
    { label: "Read.cv", href: "#" },
  ];

  return (
    <>
      {showPopup && <DiscordPopup onClose={() => setShowPopup(false)} />}
      <RevealText delay={0} className="section-label"><span>{c.label}</span></RevealText>
      <div style={{ marginTop: "clamp(32px, 5vh, 56px)" }}>
        <RevealWords delay={100} className="contact-title">{c.title.split("\n")[0]}</RevealWords>
        <RevealWords delay={180} className="contact-title">{c.title.split("\n")[1]}</RevealWords>
      </div>
      <RevealText delay={300}>
        <p style={{ fontFamily: "'DM Sans', sans-serif", fontWeight: 300, fontSize: "clamp(14px, 1.2vw, 17px)", color: "#555", lineHeight: 1.7, maxWidth: 400, marginTop: "clamp(16px, 2.5vh, 28px)", marginBottom: "clamp(40px, 7vh, 80px)" }}>{c.subtitle}</p>
      </RevealText>
      <RevealText delay={380}>
        <MagneticElement strength={0.2} style={{ display: "inline-block" }}>
          <a href={`mailto:${c.email}`} className="cursor-link"
            onMouseEnter={() => setEmailHovered(true)} onMouseLeave={() => setEmailHovered(false)}
            style={{ display: "inline-block", fontFamily: "'Cormorant Garamond', serif", fontWeight: 300, fontSize: "clamp(28px, 4vw, 60px)", letterSpacing: "-0.01em", color: emailHovered ? "#ededeb" : "#666", textDecoration: "none", transition: "color 0.4s cubic-bezier(0.16,1,0.3,1)", borderBottom: `1px solid ${emailHovered ? "#3a3a3a" : "#1e1e1e"}`, paddingBottom: "0.05em" }}>
            {c.email}
          </a>
        </MagneticElement>
      </RevealText>
      <div style={{ marginTop: "clamp(48px, 8vh, 96px)", display: "flex", flexWrap: "wrap", justifyContent: "space-between", gap: "clamp(32px, 5vw, 80px)", alignItems: "flex-end" }}>
        <RevealText delay={460}>
          <div style={{ display: "flex", gap: "clamp(20px, 2.5vw, 36px)", flexWrap: "wrap", alignItems: "center" }}>
            {socials.map(s => (
              <MagneticElement key={s.label} strength={0.5}>
                <a href={s.href} className="social-link cursor-link" onClick={e => e.preventDefault()}>{s.label}</a>
              </MagneticElement>
            ))}
            <MagneticElement strength={0.5}>
              <button onClick={() => setShowPopup(true)} className="cursor-link"
                style={{ background: 'none', border: 'none', display: 'flex', alignItems: 'center', gap: 6, fontFamily: "'DM Mono', monospace", fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#333', transition: 'color 0.3s ease', paddingBottom: 2, borderBottom: '1px solid transparent' }}
                onMouseEnter={e => e.currentTarget.style.color='#999'} onMouseLeave={e => e.currentTarget.style.color='#333'}
              >
                <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: statusDotColor[status], boxShadow: status==='online'?'0 0 6px #23a55a66':'' }} />
                Discord
              </button>
            </MagneticElement>
          </div>
        </RevealText>
        <RevealText delay={500}><LanyardWidget /></RevealText>
      </div>
    </>
  );
}

function useScramble(original, active) {
  const [display, setDisplay] = React.useState(original);
  const chars = '!<>-_\/[]{}—=+*^?#@0123456789abcdefghijklmnopqrstuvwxyz';

  React.useEffect(() => {
    if (!active) { setDisplay(original); return; }
    let iter = 0;
    const total = original.length;
    const interval = setInterval(() => {
      setDisplay(
        original.split('').map((ch, i) => {
          if (ch === '@' || ch === '.') return ch;
          if (i < iter) return original[i];
          return chars[Math.floor(Math.random() * chars.length)];
        }).join('')
      );
      if (iter >= total) clearInterval(interval);
      iter += 0.5;
    }, 28);
    return () => clearInterval(interval);
  }, [active, original]);

  return display;
}

function AmbientGrain({ visible }) {
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(null);

  React.useEffect(() => {
    if (!visible) return;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let W, H;

    const resize = () => {
      W = canvas.width = canvas.clientWidth;
      H = canvas.height = canvas.clientHeight;
    };
    resize();
    window.addEventListener('resize', resize);

    let frame = 0;
    const render = () => {
      frame++;
      if (frame % 2 === 0) {
        const imageData = ctx.createImageData(W, H);
        const data = imageData.data;
        for (let i = 0; i < data.length; i += 4) {
          const v = Math.random() * 255;
          data[i] = data[i+1] = data[i+2] = v;
          data[i+3] = Math.random() * 18;
        }
        ctx.putImageData(imageData, 0, 0);

        const vg = ctx.createRadialGradient(W/2, H/2, H*0.15, W/2, H/2, H*0.75);
        vg.addColorStop(0, 'rgba(6,6,8,0)');
        vg.addColorStop(1, 'rgba(6,6,8,0.55)');
        ctx.fillStyle = vg;
        ctx.fillRect(0, 0, W, H);
      }
      rafRef.current = requestAnimationFrame(render);
    };
    rafRef.current = requestAnimationFrame(render);
    return () => { cancelAnimationFrame(rafRef.current); window.removeEventListener('resize', resize); };
  }, [visible]);

  if (!visible) return null;
  return <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', mixBlendMode: 'screen', opacity: 0.55 }} />;
}

function AmbientEcho({ visible, email }) {
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(null);

  React.useEffect(() => {
    if (!visible) return;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let W, H;

    const resize = () => {
      W = canvas.width = canvas.clientWidth;
      H = canvas.height = canvas.clientHeight;
    };
    resize();
    window.addEventListener('resize', resize);

    const t0 = performance.now();
    const layers = [
      { size: 0.085, alpha: 0.032, y: 0.5,  x: 0.5,  drift: 0.0008,  rot: 0 },
      { size: 0.052, alpha: 0.022, y: 0.72, x: 0.44, drift: -0.0005, rot: -0.015 },
      { size: 0.038, alpha: 0.018, y: 0.3,  x: 0.56, drift: 0.0006,  rot: 0.02 },
    ];

    const render = () => {
      const t = (performance.now() - t0) / 1000;
      ctx.clearRect(0, 0, W, H);

      layers.forEach((l, i) => {
        const fontSize = W * l.size;
        ctx.save();
        ctx.translate(W * l.x + Math.sin(t * 0.12 + i) * 8, H * l.y + Math.cos(t * 0.09 + i * 1.3) * 5);
        ctx.rotate(l.rot + Math.sin(t * 0.05 + i) * 0.005);
        ctx.font = `300 ${fontSize}px 'Cormorant Garamond', serif`;
        ctx.fillStyle = `rgba(237,237,235,${l.alpha})`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(email, 0, 0);
        ctx.restore();
      });

      rafRef.current = requestAnimationFrame(render);
    };
    rafRef.current = requestAnimationFrame(render);
    return () => { cancelAnimationFrame(rafRef.current); window.removeEventListener('resize', resize); };
  }, [visible, email]);

  if (!visible) return null;
  return <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }} />;
}

function AmbientLines({ visible }) {
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(null);

  React.useEffect(() => {
    if (!visible) return;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let W, H;

    const resize = () => {
      W = canvas.width = canvas.clientWidth;
      H = canvas.height = canvas.clientHeight;
    };
    resize();
    window.addEventListener('resize', resize);

    const t0 = performance.now();
    const lines = [
      { x: 0.18, speed: 0.006,  angle: 0,     alpha: 0.07, width: 0.5 },
      { x: 0.42, speed: -0.004, angle: 0,     alpha: 0.045, width: 0.5 },
      { x: 0.67, speed: 0.003,  angle: 0.04,  alpha: 0.06, width: 0.5 },
      { x: 0.83, speed: -0.007, angle: -0.03, alpha: 0.04, width: 0.5 },
      { x: 0.55, speed: 0.005,  angle: 0,     alpha: 0.03, width: 1   },
    ];

    const render = () => {
      const t = (performance.now() - t0) / 1000;
      ctx.clearRect(0, 0, W, H);

      lines.forEach((l, i) => {
        const x = ((l.x + t * l.speed * 0.05) % 1) * W;
        const pulse = 0.5 + Math.sin(t * 0.4 + i * 1.2) * 0.5;
        ctx.save();
        ctx.translate(x, H / 2);
        ctx.rotate(l.angle);

        const grad = ctx.createLinearGradient(0, -H * 0.6, 0, H * 0.6);
        grad.addColorStop(0,   `rgba(237,237,235,0)`);
        grad.addColorStop(0.3, `rgba(237,237,235,${l.alpha * pulse})`);
        grad.addColorStop(0.7, `rgba(237,237,235,${l.alpha * pulse})`);
        grad.addColorStop(1,   `rgba(237,237,235,0)`);

        ctx.strokeStyle = grad;
        ctx.lineWidth = l.width;
        ctx.beginPath();
        ctx.moveTo(0, -H * 0.6);
        ctx.lineTo(0,  H * 0.6);
        ctx.stroke();
        ctx.restore();
      });

      rafRef.current = requestAnimationFrame(render);
    };
    rafRef.current = requestAnimationFrame(render);
    return () => { cancelAnimationFrame(rafRef.current); window.removeEventListener('resize', resize); };
  }, [visible]);

  if (!visible) return null;
  return <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }} />;
}

function ContactSectionCentered({ c, t, scramble = true, ambientRing = 'grain' }) {
  const [showPopup, setShowPopup] = React.useState(false);
  const [emailHovered, setEmailHovered] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const [cvOpen, setCvOpen] = React.useState(false);
  const cvWrapRef = React.useRef(null);
  const scrambledEmail = useScramble(c.email, scramble && emailHovered && !copied);
  const { data } = useLanyard(LANYARD_USER_ID);
  const status = data?.discord_status || 'offline';
  const statusDotColor = { online: '#23a55a', idle: '#f0b232', dnd: '#f23f43', offline: '#80848e' };

  React.useEffect(() => {
    if (!cvOpen) return;
    const onClickOutside = (e) => {
      if (cvWrapRef.current && !cvWrapRef.current.contains(e.target)) setCvOpen(false);
    };
    document.addEventListener('mousedown', onClickOutside);
    return () => document.removeEventListener('mousedown', onClickOutside);
  }, [cvOpen]);

  const socials = [
    { label: "GitHub",   iconKey: "github",   href: "https://github.com/muuqi111" },
    { label: "LinkedIn", iconKey: "linkedin", href: "https://www.linkedin.com/in/mustafa-ok-dev/" },
  ];

  return (
    <>
      {showPopup && <DiscordPopup onClose={() => setShowPopup(false)} />}
      {ambientRing === 'grain' && <AmbientGrain visible={true} />}
      {ambientRing === 'echo' && <AmbientEcho visible={true} email={c.email} />}
      {ambientRing === 'lines' && <AmbientLines visible={true} />}

      <div style={{ textAlign: 'center', maxWidth: 700, margin: '0 auto', position: 'relative', zIndex: 1 }}>
        <RevealText delay={0} className="section-label" style={{ justifyContent: 'center' }}><span>{c.label}</span></RevealText>

        <RevealText delay={120}>
          <MagneticElement strength={0.15} style={{ display: 'block', marginTop: 'clamp(24px, 4vh, 48px)' }}>
            <div style={{ position: 'relative', display: 'inline-block', width: '100%' }}>
              <button
                className="cursor-link"
                onMouseEnter={() => setEmailHovered(true)}
                onMouseLeave={() => setEmailHovered(false)}
                onClick={() => {
                  navigator.clipboard.writeText(c.email).then(() => setCopied(true));
                  setTimeout(() => setCopied(false), 2200);
                }}
                style={{
                  background: 'none', border: 'none', padding: 0, width: '100%',
                  fontFamily: "'Cormorant Garamond', serif", fontWeight: 300,
                  fontSize: "clamp(32px, 5.5vw, 80px)", letterSpacing: "-0.02em",
                  color: copied ? "#ededeb" : emailHovered ? "#ededeb" : "#ccc",
                  transition: "color 0.4s ease", lineHeight: 1,
                  fontVariantNumeric: 'tabular-nums',
                  display: 'block',
                }}>
                {copied ? 'Copied ✓' : scrambledEmail}
              </button>
            </div>
          </MagneticElement>
        </RevealText>

        <RevealText delay={280}>
          <p style={{ fontFamily: "'DM Sans', sans-serif", fontWeight: 300, fontSize: "clamp(13px, 1.1vw, 16px)", color: "#444", marginTop: "clamp(16px, 2.5vh, 28px)", marginBottom: "clamp(48px, 8vh, 80px)" }}>{c.subtitle}</p>
        </RevealText>

        <RevealText delay={360}>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 'clamp(28px, 5vw, 56px)', alignItems: 'center' }}>
            {socials.map(s => (
              <MagneticElement key={s.label} strength={0.6}>
                <a href={s.href} target="_blank" rel="noopener noreferrer" className="cursor-link"
                  style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, textDecoration: 'none', color: '#333', transition: 'color 0.3s ease' }}
                  onMouseEnter={e => e.currentTarget.style.color='#888'} onMouseLeave={e => e.currentTarget.style.color='#333'}
                >
                  <div style={{ width: 42, height: 42, border: '1px solid #1a1a1a', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'border-color 0.3s ease', color: 'inherit' }}>
                    {ICONS[s.iconKey]}
                  </div>
                  <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 8.5, letterSpacing: '0.28em', textTransform: 'uppercase' }}>{s.label}</span>
                </a>
              </MagneticElement>
            ))}

            <MagneticElement strength={0.6}>
              <div
                ref={cvWrapRef}
                className={`cv-morph-wrap${cvOpen ? ' is-open' : ''}`}
                onClick={() => setCvOpen(true)}
              >
                <div className="cv-morph-trigger">
                  <span className="cv-morph-icon">{ICONS.cv}</span>
                  <div className="cv-morph-segments">
                    <a href="cv-fr.pdf" download className="cv-morph-seg cursor-link"
                      onClick={(e) => { e.stopPropagation(); setCvOpen(false); }}
                    >FR</a>
                    <a href="cv-en.pdf" download className="cv-morph-seg cursor-link"
                      onClick={(e) => { e.stopPropagation(); setCvOpen(false); }}
                    >EN</a>
                  </div>
                </div>
                <span className="cv-morph-label">CV</span>
              </div>
            </MagneticElement>

            <MagneticElement strength={0.6}>
              <button onClick={() => setShowPopup(true)} className="cursor-link"
                style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, background: 'none', border: 'none', color: '#333', transition: 'color 0.3s ease' }}
                onMouseEnter={e => e.currentTarget.style.color='#888'} onMouseLeave={e => e.currentTarget.style.color='#333'}
              >
                <div style={{ width: 42, height: 42, border: '1px solid #1a1a1a', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', transition: 'border-color 0.3s ease' }}>
                  {ICONS.discord}
                  <span style={{ position: 'absolute', bottom: 0, right: 0, width: 9, height: 9, borderRadius: '50%', background: statusDotColor[status], border: '2px solid #060608', boxShadow: status==='online'?'0 0 5px #23a55a66':'' }} />
                </div>
                <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 8.5, letterSpacing: '0.28em', textTransform: 'uppercase' }}>Discord</span>
              </button>
            </MagneticElement>
          </div>
        </RevealText>
      </div>
    </>
  );
}

function ContactSection({ layout = 'centered', scramble = true, ambientRing = 'grain' }) {
  const { t } = useI18n();
  const c = t.contact;

  return (
    <section id="contact" data-screen-label="05 Contact"
      style={{ minHeight: "90vh", display: "flex", flexDirection: "column", justifyContent: "center", padding: "clamp(80px, 14vh, 160px) clamp(24px, 8vw, 120px)", borderTop: "1px solid #161616", position: "relative", overflow: "hidden" }}
    >
      {layout === 'editorial'
        ? <ContactSectionEditorial c={c} t={t} />
        : <ContactSectionCentered c={c} t={t} scramble={scramble} ambientRing={ambientRing} />}

      <div style={{ position: "absolute", bottom: "clamp(20px, 3vh, 36px)", left: "clamp(24px, 8vw, 120px)", right: "clamp(24px, 8vw, 120px)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, letterSpacing: "0.2em", color: "#444", textTransform: "uppercase" }}>muuqi · {new Date().getFullYear()}</span>
        <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, letterSpacing: "0.14em", color: "#444" }}>Designed & built by muuqi</span>
      </div>
    </section>
  );
}

Object.assign(window, { ContactSection });
