// Shared components for Split Crew landing page

function HexBg({ density = 1, accent = false }) {
  // Hex grid using tiled pattern
  const size = 26;
  const patternId = `hex-${Math.random().toString(36).slice(2, 8)}`;
  return (
    <div className="hex-bg">
      <svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice">
        <defs>
          <pattern id={patternId} width={size * 1.732} height={size * 3} patternUnits="userSpaceOnUse">
            {/* Two hexagons offset to tile */}
            <g fill="none" stroke={accent ? 'rgba(59,180,232,0.35)' : 'rgba(59,180,232,0.22)'} strokeWidth="0.6">
              <polygon points={hexPoints(size * 0.866, size * 0.75, size * 0.75)} />
              <polygon points={hexPoints(size * 1.732, size * 2.25, size * 0.75)} />
              <polygon points={hexPoints(0, size * 2.25, size * 0.75)} />
            </g>
          </pattern>
          <radialGradient id={`${patternId}-fade`} cx="50%" cy="40%" r="70%">
            <stop offset="0%" stopColor="white" stopOpacity="1" />
            <stop offset="100%" stopColor="white" stopOpacity="0.2" />
          </radialGradient>
          <mask id={`${patternId}-mask`}>
            <rect width="100%" height="100%" fill={`url(#${patternId}-fade)`} />
          </mask>
        </defs>
        <rect width="100%" height="100%" fill={`url(#${patternId})`} mask={`url(#${patternId}-mask)`} />
      </svg>
    </div>
  );
}

function hexPoints(cx, cy, r) {
  const pts = [];
  for (let i = 0; i < 6; i++) {
    const a = (Math.PI / 3) * i + Math.PI / 6;
    pts.push(`${(cx + r * Math.cos(a)).toFixed(2)},${(cy + r * Math.sin(a)).toFixed(2)}`);
  }
  return pts.join(' ');
}

// Small stat/pagination dots like the reference
function Dots({ total = 8, active = 3 }) {
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
      {Array.from({ length: total }).map((_, i) => (
        <span key={i} style={{
          width: 8, height: 8, borderRadius: '50%',
          border: '1px solid var(--cyan-500)',
          background: i === active ? 'var(--cyan-500)' : 'transparent',
          boxShadow: i === active ? '0 0 8px var(--cyan-500)' : 'none',
        }} />
      ))}
    </div>
  );
}

function BackArrow() {
  return (
    <div style={{
      width: 44, height: 44, borderRadius: '50%',
      border: '1.5px solid var(--cyan-500)',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      color: 'var(--cyan-100)', cursor: 'pointer',
      transition: 'all .18s',
    }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
        <path d="M19 12H5M12 19l-7-7 7-7" />
      </svg>
    </div>
  );
}

// Crew avatar - silhouette style matching the reference, supports optional photo
function CrewAvatar({ color, initial, size = 40, photo = null }) {
  if (photo) {
    return (
      <div style={{
        width: size, height: size,
        borderRadius: '50%',
        border: `1.5px solid ${color}`,
        backgroundImage: `url(${photo})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        boxShadow: `0 0 12px ${color}44`,
        flexShrink: 0,
      }} />
    );
  }
  return (
    <div style={{
      width: size, height: size,
      borderRadius: '50%',
      background: `linear-gradient(180deg, ${color}22, ${color}08)`,
      border: `1.5px solid ${color}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-display)',
      fontWeight: 700,
      fontSize: size * 0.4,
      color: color,
      letterSpacing: '0.05em',
      boxShadow: `0 0 12px ${color}44`,
      flexShrink: 0,
    }}>{initial}</div>
  );
}

// Profile store — centralised "Du" identity
const PROFILE_KEY = 'sc-me-profile';

// Stable per-device identifier — generated once, persisted forever.
// Used by Supabase to dedupe members on (crew_id, device_id).
const DEVICE_ID_KEY = 'tt-device-id';
function getDeviceId() {
  let id = null;
  try { id = localStorage.getItem(DEVICE_ID_KEY); } catch (e) {}
  if (id && id.length > 8) return id;
  // crypto.randomUUID is widely supported on iOS 14+/modern browsers.
  // Fallback: time + random bytes for older runtimes.
  if (window.crypto && window.crypto.randomUUID) id = window.crypto.randomUUID();
  else id = 'dev-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 12);
  try { localStorage.setItem(DEVICE_ID_KEY, id); } catch (e) {}
  return id;
}

function useMe() {
  const [me, setMe] = React.useState(() => {
    try {
      const raw = localStorage.getItem(PROFILE_KEY);
      if (raw) return JSON.parse(raw);
    } catch(e) {}
    return { name: 'Du', photo: null };
  });
  const save = (next) => {
    setMe(next);
    try { localStorage.setItem(PROFILE_KEY, JSON.stringify(next)); } catch(e) {}
    // Tell other mounted AppFlows to refresh
    window.dispatchEvent(new CustomEvent('me-updated'));
  };
  React.useEffect(() => {
    const h = () => {
      try { const raw = localStorage.getItem(PROFILE_KEY); if (raw) setMe(JSON.parse(raw)); } catch(e){}
    };
    window.addEventListener('me-updated', h);
    return () => window.removeEventListener('me-updated', h);
  }, []);
  return [me, save];
}

function MeAvatar({ size = 40 }) {
  const [me] = useMe();
  const initial = (me.name || 'Du').trim().charAt(0).toUpperCase() || 'D';
  return <CrewAvatar color="#3BB4E8" initial={initial} size={size} photo={me.photo} />;
}

// Logo mark — hex + split
function Logo({ size = 28 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
        <polygon points="16,2 29,9 29,23 16,30 3,23 3,9" stroke="var(--cyan-500)" strokeWidth="1.5" fill="rgba(59,180,232,0.08)" />
        <line x1="16" y1="2" x2="16" y2="30" stroke="var(--cyan-500)" strokeWidth="1.5" />
        <circle cx="16" cy="16" r="3" fill="var(--cyan-500)" />
      </svg>
      <span style={{
        fontFamily: 'var(--font-display)', fontWeight: 700,
        letterSpacing: '0.22em', fontSize: 15,
        color: 'var(--text-hi)', textTransform: 'uppercase',
      }}>Split<span style={{ color: 'var(--cyan-500)' }}>Crew</span></span>
    </div>
  );
}

Object.assign(window, { HexBg, Dots, BackArrow, CrewAvatar, Logo, useMe, MeAvatar, getDeviceId });
