// components.jsx — Atoms shared across screens

const { useState, useEffect, useRef, useMemo } = React;

// ─── Logo ────────────────────────────────────────────────────────────────
function PokerChip({ size = 22, color = 'var(--gold)' }) {
  // A round poker chip with cross-hatched edge bites and a center pip.
  const s = size;
  return (
    <svg width={s} height={s} viewBox="0 0 24 24" style={{ display: 'inline-block', flexShrink: 0 }}>
      <defs>
        <radialGradient id="chipShine" cx="35%" cy="30%" r="70%">
          <stop offset="0%" stopColor="rgba(255,255,255,0.35)"/>
          <stop offset="60%" stopColor="rgba(255,255,255,0)"/>
        </radialGradient>
      </defs>
      {/* Outer rim */}
      <circle cx="12" cy="12" r="11" fill={color}/>
      {/* Edge dashes (chip bites) */}
      {[0,1,2,3,4,5,6,7].map(i => {
        const a = (i * 360) / 8;
        return (
          <rect key={i} x="11" y="0.6" width="2" height="4.2"
                fill="#0e1422" opacity="0.85"
                transform={`rotate(${a} 12 12)`}/>
        );
      })}
      {/* Inner ring */}
      <circle cx="12" cy="12" r="7.5" fill="#0e1422"/>
      <circle cx="12" cy="12" r="6.5" fill={color}/>
      {/* Center pip */}
      <circle cx="12" cy="12" r="4" fill="#0e1422"/>
      <text x="12" y="15.3" textAnchor="middle"
            fontFamily="Instrument Serif, Georgia, serif"
            fontSize="6.5" fill={color} fontStyle="italic" fontWeight="700">PL</text>
      {/* Highlight */}
      <circle cx="12" cy="12" r="11" fill="url(#chipShine)"/>
    </svg>
  );
}

function Wordmark({ small }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: small ? 6 : 8 }}>
      <PokerChip size={small ? 20 : 26} color="var(--gold)"/>
      <div style={{ display: 'inline-flex', flexDirection: 'column', lineHeight: 1 }}>
        <div className="mono" style={{
          fontSize: small ? 7 : 8, color: 'var(--gold)',
          letterSpacing: '0.28em', fontWeight: 600,
          marginBottom: 1,
        }}>
          pokerlatereg.com
        </div>
        <div className="serif" style={{
          fontSize: small ? 20 : 25, color: 'var(--ivory-d)',
          letterSpacing: '-0.02em', lineHeight: 0.95,
          fontStyle: 'italic', whiteSpace: 'nowrap',
        }}>
          Poker<span style={{ color: 'var(--gold)' }}>LateReg</span>
        </div>
      </div>
    </div>
  );
}

// ─── Doyle avatar ───────────────────────────────────────────────────────
function CoachAvatar({ size = 36, mode = 'sharp', talking = false }) {
  const ringColor = mode === 'sharp' ? 'var(--red-bright)' : mode === 'mentor' ? 'var(--gold)' : 'var(--green-bright)';
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: 'linear-gradient(145deg, #2a2a30, #15151a)',
      border: `1.5px solid ${ringColor}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-serif)', color: 'var(--ivory-d)',
      fontSize: size * 0.42, position: 'relative', flexShrink: 0,
      boxShadow: talking ? `0 0 0 0 ${ringColor}` : 'none',
      animation: talking ? 'pulse 1.4s infinite' : 'none',
    }}>
      A
    </div>
  );
}

// ─── Live countdown ──────────────────────────────────────────────────────
function Countdown({ target, big = false, urgent: forceUrgent }) {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  const diff = Math.max(0, Math.floor((target.getTime() - now.getTime()) / 1000));
  const h = Math.floor(diff / 3600);
  const m = Math.floor((diff % 3600) / 60);
  const s = diff % 60;
  const urgent = forceUrgent ?? diff < 600;
  const expired = diff === 0;
  const color = expired ? 'var(--muted-d)' : urgent ? 'var(--red-bright)' : 'var(--gold)';
  return (
    <span className="num" style={{
      color, fontWeight: 500,
      fontVariantNumeric: 'tabular-nums',
      fontSize: big ? 56 : 'inherit',
      letterSpacing: big ? '-0.04em' : '-0.01em',
      animation: urgent && big ? 'flashRed 1s infinite' : 'none',
    }}>
      {h > 0 ? `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}` : `${m}:${String(s).padStart(2,'0')}`}
    </span>
  );
}

// ─── Doyle take pill ────────────────────────────────────────────────────
function AndrewTake({ take }) {
  const map = {
    go:    { label: 'GO',    cls: 'tag-green' },
    skip:  { label: 'SKIP',  cls: 'tag-red'   },
    pass:  { label: 'PASS',  cls: 'tag-amber' },
    maybe: { label: 'MAYBE', cls: 'tag-amber' },
  };
  const m = map[take] || map.maybe;
  return <span className={`tag ${m.cls}`} style={{ fontWeight: 600 }}>D · {m.label}</span>;
}

// ─── Tournament card ─────────────────────────────────────────────────────
function TournamentCard({ t, onTap, compact }) {
  const closingFast = (t.regClose.getTime() - Date.now()) < 15 * 60 * 1000;
  return (
    <button onClick={() => onTap?.(t)} style={{
      all: 'unset', cursor: 'pointer',
      display: 'block', width: '100%',
      padding: '16px 20px',
      borderTop: '1px solid var(--line-d)',
      transition: 'background 150ms var(--ease)',
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--felt-2)'}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 10 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
            <span className="tag tag-gold">{t.tag}</span>
            <span className="eyebrow" style={{ color: 'var(--paper-d)' }}>{t.casino}</span>
          </div>
          <div className="serif" style={{ fontSize: 22, lineHeight: 1.1, marginBottom: 2 }}>{t.title}</div>
          <div className="mono" style={{ fontSize: 12, color: 'var(--muted-d)' }}>
            ${t.buyin.toLocaleString()} · {t.room} · L{t.level}
          </div>
        </div>
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div className="eyebrow" style={{ marginBottom: 2 }}>Reg closes</div>
          <div style={{ fontSize: 22, fontWeight: 500 }}>
            <Countdown target={t.regClose} urgent={closingFast} />
          </div>
        </div>
      </div>

      {!compact && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, padding: '10px 0', borderTop: '1px solid var(--line-d)' }}>
          <Stat label="Field" value={t.field ? t.field.toLocaleString() : '—'} sub={t.chipAvg ? `avg ${(t.chipAvg/1000).toFixed(1)}k` : 'starts soon'} />
          <Stat label="Walk" value={t.walkMin ? `${t.walkMin} min` : t.distance} sub={t.walkMin ? t.distance : ''} />
          <Stat label="Pool" value={t.prizePool ? `$${(t.prizePool/1000).toFixed(0)}k` : '—'} sub={`Struct ${t.structureGrade}`} />
        </div>
      )}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginTop: 8 }}>
        <AndrewTake take={t.doyle.take} />
        <div style={{ fontSize: 12, color: 'var(--paper-d)', textAlign: 'right', flex: 1, minWidth: 0,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          "{t.doyle.note}"
        </div>
      </div>

      {t.friends.length > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10 }}>
          <div style={{ display: 'flex' }}>
            {t.friends.slice(0,3).map((f,i) => (
              <div key={i} style={{
                width: 22, height: 22, borderRadius: '50%',
                background: 'var(--felt-3)', border: '1.5px solid var(--felt)',
                marginLeft: i === 0 ? 0 : -7, fontSize: 11,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{f.avatar}</div>
            ))}
          </div>
          <span className="mono" style={{ fontSize: 11, color: 'var(--paper-d)' }}>
            {t.friends.map(f => f.name).join(', ')} {t.friends.length > 1 ? 'are in' : 'is in'}
          </span>
        </div>
      )}
    </button>
  );
}

function Stat({ label, value, sub }) {
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 2 }}>{label}</div>
      <div className="num" style={{ fontSize: 14, fontWeight: 500, color: 'var(--ivory-d)' }}>{value}</div>
      {sub && <div className="mono" style={{ fontSize: 10, color: 'var(--muted-d)', marginTop: 1 }}>{sub}</div>}
    </div>
  );
}

// ─── Bottom Nav ──────────────────────────────────────────────────────────
function BottomNav({ active, onTab, onPokerLateReg }) {
  const tabs = [
    { id: 'home',    label: 'Late Reg', icon: 'clock' },
    { id: 'coach',   label: 'Kyle',    icon: 'doyle' },
    { id: 'friends', label: 'Friends',  icon: 'users' },
    { id: 'fantasy', label: 'Fantasy',  icon: 'fantasy' },
    { id: 'me',      label: 'Me',       icon: 'user' },
  ];
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0,
      background: 'rgba(10,10,11,0.92)',
      backdropFilter: 'blur(18px) saturate(180%)',
      WebkitBackdropFilter: 'blur(18px) saturate(180%)',
      borderTop: '1px solid var(--line-d)',
      paddingBottom: 28, paddingTop: 8,
      display: 'flex', justifyContent: 'space-around', alignItems: 'flex-end',
      zIndex: 50,
    }}>
      {tabs.map(t => (
        <button key={t.id} onClick={() => onTab(t.id)} style={{
          all: 'unset', cursor: 'pointer',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
          padding: '6px 10px', flex: 1,
          color: active === t.id ? 'var(--gold)' : 'var(--muted-d)',
          transition: 'color 150ms var(--ease)',
        }}>
          <NavIcon id={t.icon} />
          <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{t.label}</span>
        </button>
      ))}
    </div>
  );
}

function NavIcon({ id }) {
  const s = { width: 22, height: 22, fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (id) {
    case 'clock':   return <svg {...s}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    case 'users':   return <svg {...s}><circle cx="9" cy="8" r="3.2"/><path d="M3.5 19c0-3 2.5-5.5 5.5-5.5s5.5 2.5 5.5 5.5"/><circle cx="16" cy="8" r="2.5"/><path d="M16 13c2 0 4 1.5 4 4"/></svg>;
    case 'moon':    return <svg {...s}><path d="M20 13a8 8 0 1 1-9-9 6 6 0 0 0 9 9z"/></svg>;
    case 'user':    return <svg {...s}><circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-3.5 3-6 7-6s7 2.5 7 6"/></svg>;
    case 'doyle':  return (
      <svg viewBox="0 0 24 24" style={{ width: 22, height: 22 }}>
        <circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" strokeWidth="1.5"/>
        <text x="12" y="15.5" textAnchor="middle" fontFamily="var(--font-serif)" fontSize="11" fill="currentColor">A</text>
        <text x="17" y="11" fontFamily="var(--font-mono)" fontSize="6" fill="var(--gold)">1</text>
      </svg>
    );
    case 'fantasy': return (
      <svg viewBox="0 0 24 24" style={{ width: 22, height: 22, fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' }}>
        <polygon points="12,3 14.5,9 21,9.5 16,13.5 17.5,20 12,16.5 6.5,20 8,13.5 3,9.5 9.5,9"/>
      </svg>
    );
    default: return null;
  }
}

// ─── Header ──────────────────────────────────────────────────────────────
function AppHeader({ title, eyebrow, right, onHelp }) {
  return (
    <div style={{ padding: '8px 20px 12px', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
      <div style={{ minWidth: 0 }}>
        {eyebrow && <div className="eyebrow" style={{ color: 'var(--gold)', marginBottom: 4 }}>{eyebrow}</div>}
        <h1 className="serif" style={{ fontSize: 30, lineHeight: 1, margin: 0 }}>{title}</h1>
      </div>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>
        {right}
        {onHelp && (
          <button onClick={onHelp} className="btn btn-ghost" style={{ padding: '6px 8px', fontSize: 11 }} title="Responsible gambling">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 0 1 5 0c0 1.5-2.5 2-2.5 4"/><circle cx="12" cy="17" r="0.6" fill="currentColor"/></svg>
          </button>
        )}
      </div>
    </div>
  );
}

// ─── Pacific Time clock ─────────────────────────────────────────────────
function PacificClock() {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 30000);
    return () => clearInterval(t);
  }, []);
  // We're using the "fake now" for the prototype
  const fake = new Date(window.APP_DATA.NOW.getTime() + (Date.now() - window.__bootTime));
  const hh = fake.getHours();
  const mm = fake.getMinutes();
  const ampm = hh >= 12 ? 'PM' : 'AM';
  const h = ((hh + 11) % 12) + 1;
  return (
    <span className="mono" style={{ fontSize: 11, color: 'var(--paper-d)', letterSpacing: '0.05em' }}>
      {h}:{String(mm).padStart(2,'0')} {ampm} · PT
    </span>
  );
}

// Boot reference time
window.__bootTime = window.__bootTime || Date.now();

// ─── Friend dot for map ──────────────────────────────────────────────────
function FriendDot({ friend, x, y, onTap }) {
  const color = friend.status === 'alive' ? 'var(--green-bright)' : friend.status === 'busted' ? 'var(--red-bright)' : 'var(--amber-c)';
  return (
    <button onClick={() => onTap?.(friend)} style={{
      all: 'unset', cursor: 'pointer',
      position: 'absolute', left: `${x}%`, top: `${y}%`, transform: 'translate(-50%,-50%)',
    }}>
      <div style={{ position: 'relative' }}>
        <div style={{
          position: 'absolute', inset: -6, borderRadius: '50%',
          background: color, opacity: 0.4,
          animation: friend.status === 'alive' ? 'mapPulse 2.4s infinite' : 'none',
        }}/>
        <div style={{
          width: 28, height: 28, borderRadius: '50%',
          background: 'var(--felt-3)', border: `2px solid ${color}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 13, position: 'relative',
        }}>{friend.avatar}</div>
      </div>
    </button>
  );
}

// Export
Object.assign(window, {
  Wordmark, PokerChip, CoachAvatar, Countdown, AndrewTake, TournamentCard, Stat,
  BottomNav, AppHeader, PacificClock, FriendDot, NavIcon,
});
