// Starfish — bottom-left creature. Clicking reveals a small vendor-partnership card.
// Sits just above the bottom of the screen; wiggles its arms gently.

const Starfish = () => {
  const [open, setOpen] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const [t, setT] = React.useState(0);
  const triggerRef = React.useRef(null);
  const panelRef = React.useRef(null);

  // close on click outside
  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => {
      const t = e.target;
      if (triggerRef.current?.contains(t)) return;
      if (panelRef.current?.contains(t)) return;
      setOpen(false);
    };
    const id = setTimeout(() => document.addEventListener('mousedown', onDown), 0);
    return () => { clearTimeout(id); document.removeEventListener('mousedown', onDown); };
  }, [open]);

  React.useEffect(() => {
    let raf;
    const start = performance.now();
    const loop = (now) => {
      setT((now - start) / 1000);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  const rot = Math.sin(t * 0.5) * 6;      // slow sway
  const breathe = 1 + Math.sin(t * 1.2) * 0.03;

  // Classic 5-point star path — sharp, pointy arms
  const starPath = (() => {
    const pts = [];
    const R = 30, r = 13;
    for (let i = 0; i < 10; i++) {
      const angle = (Math.PI / 5) * i - Math.PI / 2;
      const rad = i % 2 === 0 ? R : r;
      pts.push([Math.cos(angle) * rad, Math.sin(angle) * rad]);
    }
    return 'M ' + pts.map(p => p.join(',')).join(' L ') + ' Z';
  })();

  // Little bumps (tubercles) scattered on the surface
  const bumps = (() => {
    const out = [];
    const rings = [
      { r: 20, count: 5, size: 1.5 },
      { r: 11, count: 5, size: 1.3 },
    ];
    rings.forEach((ring, ri) => {
      for (let i = 0; i < ring.count; i++) {
        const a = (Math.PI * 2 / ring.count) * i + (ri === 0 ? -Math.PI/2 : -Math.PI/2 + Math.PI/5);
        out.push({
          x: Math.cos(a) * ring.r,
          y: Math.sin(a) * ring.r,
          r: ring.size,
        });
      }
    });
    return out;
  })();

  const email = 'partnerships@tides.deals';
  const copy = (e) => {
    e.stopPropagation();
    navigator.clipboard?.writeText(email);
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };

  const isMobile = window.innerWidth < 600 || window.matchMedia('(pointer: coarse)').matches;
  const sfScale  = isMobile ? 0.65 : 1.12;

  return (
    <>
      {/* Creature — bottom-RIGHT with hint */}
      <div
        style={{
          position: 'fixed',
          right: isMobile ? 14 : 36,
          bottom: isMobile ? 14 : 28,
          zIndex: 50,
          pointerEvents: 'none',
          display: 'flex',
          flexDirection: 'row-reverse',
          alignItems: 'center',
          gap: isMobile ? 6 : 12,
        }}
      >
        <div
          ref={triggerRef}
          style={{
            position: 'relative',
            width: isMobile ? 52 : 80,
            height: isMobile ? 52 : 80,
            pointerEvents: 'auto',
            cursor: 'none',
          }}
          onClick={() => setOpen(o => !o)}
        >
          {/* pulsing attention ring */}
          {!open && (
            <span
              style={{
                position: 'absolute',
                inset: 0,
                borderRadius: '50%',
                border: '1.5px solid rgba(198,93,79,0.55)',
                animation: 'starPulse 2.2s ease-out infinite',
                pointerEvents: 'none',
              }}
            />
          )}
          <svg
            width="80" height="80" viewBox="-40 -40 80 80"
            style={{
              display: 'block',
              overflow: 'visible',
              transform: `rotate(${rot}deg) scale(${breathe * sfScale})`,
              transition: 'filter 0.25s ease',
              filter: open ? 'drop-shadow(0 6px 14px rgba(198,93,79,0.35))' : 'none',
            }}
          >
            {/* soft water shadow behind */}
            <path d={starPath} fill="rgba(26,58,74,0.14)" transform="translate(1.2, 2.5)" />
            {/* main body — flat painterly fill, ink linework */}
            <path d={starPath} fill="#D98A6E" stroke="var(--ink)" strokeWidth="1.4" strokeLinejoin="round" />
            {/* subtle rim shading */}
            <path d={starPath} fill="rgba(122,48,36,0.18)" transform="translate(0.5, 1.2) scale(0.96)" style={{ mixBlendMode: 'multiply' }} />
            {/* surface speckles */}
            {bumps.map((b, i) => (
              <circle key={i} cx={b.x} cy={b.y} r={b.r * 0.7} fill="rgba(26,58,74,0.32)" />
            ))}
            {/* tiny ink-dot face */}
            <circle cx="-3.2" cy="-2" r="1.1" fill="var(--ink)" />
            <circle cx="3.2"  cy="-2" r="1.1" fill="var(--ink)" />
            <path d="M -2.4 3 Q 0 4.6, 2.4 3" stroke="var(--ink)" strokeWidth="1.1" fill="none" strokeLinecap="round" />
          </svg>
        </div>

        {/* Hint label + arrow (mirrored, points from text toward starfish on the right) */}
        {!open && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 5,
            fontFamily: "'Fraunces', serif",
            fontStyle: 'italic',
            fontSize: isMobile ? 11 : 14,
            color: 'var(--ink)',
            opacity: 0.75,
            animation: 'hintFloat 3s ease-in-out infinite',
            whiteSpace: 'nowrap',
          }}>
            <span>vendors say hi</span>
            <svg width={isMobile ? 26 : 38} height={isMobile ? 16 : 22} viewBox="0 0 38 22" fill="none">
              <path d="M 4 9 C 12 6 24 14 32 16" stroke="currentColor" strokeWidth="1.1" strokeDasharray="3 3" fill="none" strokeLinecap="round"/>
              <path d="M 26.6 17.2 L 32 16 L 27.8 12.4" stroke="currentColor" strokeWidth="1.1" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
        )}
      </div>

      {/* Vendor card — sits to the LEFT of the starfish now */}
      <div
        ref={panelRef}
        style={{
          position: 'fixed',
          right: isMobile ? 14 : 130,
          bottom: isMobile ? 74 : 40,
          width: isMobile ? 'min(280px, calc(100vw - 28px))' : 400,
          pointerEvents: open ? 'auto' : 'none',
          opacity: open ? 1 : 0,
          transform: open ? 'translateX(0) scale(1)' : 'translateX(12px) scale(0.96)',
          transformOrigin: '100% 100%',
          transition: 'opacity 0.35s ease, transform 0.35s cubic-bezier(.2,.9,.3,1.2)',
          zIndex: 60,
        }}
      >
        <div style={{
          background: 'rgba(255,255,255,0.78)',
          backdropFilter: 'blur(14px)',
          WebkitBackdropFilter: 'blur(14px)',
          border: '1px solid rgba(26,58,74,0.12)',
          borderRadius: 18,
          padding: '22px 28px 24px',
          boxShadow: '0 18px 40px -18px rgba(26,58,74,0.35), inset 0 1px 0 rgba(255,255,255,0.7)',
          color: 'var(--ink)',
          position: 'relative',
        }}>
          <button
            onClick={(e) => { e.stopPropagation(); setOpen(false); }}
            aria-label="Close"
            style={{
              position: 'absolute', top: 8, right: 10,
              width: 22, height: 22, borderRadius: '50%',
              background: 'transparent', border: 'none',
              color: 'var(--ink)', opacity: 0.5,
              fontSize: 16, cursor: 'none', fontFamily: 'inherit', lineHeight: 1,
            }}
          >×</button>

          <div style={{
            fontSize: 10, letterSpacing: '0.22em',
            textTransform: 'uppercase', opacity: 0.55, marginBottom: 6,
          }}>For vendors</div>

          <div style={{
            fontFamily: "'Fraunces', serif",
            fontSize: 26, lineHeight: 1.15, letterSpacing: '-0.01em',
            marginBottom: 10,
          }}>
            Run a venue? Let's partner.
          </div>

          <p style={{
            fontSize: 15, lineHeight: 1.55, margin: '0 0 14px', opacity: 0.82,
            textWrap: 'pretty',
          }}>
            If you run a fun activity venue in Melbourne such as bowling, karting,
            escape rooms, mini golf, arcades etc. drop us a line!
          </p>

          <button
            onClick={copy}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              background: 'var(--ink)',
              color: 'var(--sky)',
              border: 'none',
              borderRadius: 999,
              padding: '10px 16px',
              fontSize: 13,
              fontFamily: 'inherit',
              fontWeight: 500,
              letterSpacing: '0.01em',
              cursor: 'none',
            }}
          >
            <svg width="13" height="13" viewBox="0 0 16 16" fill="none">
              <path d="M2 4 L 8 9 L 14 4" stroke="currentColor" strokeWidth="1.3" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
              <rect x="2" y="3" width="12" height="10" rx="1.5" stroke="currentColor" strokeWidth="1.3" fill="none"/>
            </svg>
            {copied ? 'Copied!' : 'partnerships@tides.deals'}
          </button>
        </div>
      </div>
    </>
  );
};

window.Starfish = Starfish;

// Inject keyframes once
if (typeof document !== 'undefined' && !document.getElementById('starfish-kf')) {
  const s = document.createElement('style');
  s.id = 'starfish-kf';
  s.textContent = `
    @keyframes starPulse {
      0%   { transform: scale(1);   opacity: 0.55; }
      70%  { transform: scale(1.6); opacity: 0;    }
      100% { transform: scale(1.6); opacity: 0;    }
    }
    @keyframes hintFloat {
      0%,100% { transform: translateX(0); opacity: 0.75; }
      50%     { transform: translateX(3px); opacity: 1;    }
    }
  `;
  document.head.appendChild(s);
}
