/* global React, StatusBar, Wordmark, findTeam, TFApi */
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;

function SettingsIcon({ color = '#fff' }) {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <circle cx="5" cy="12" r="2" fill={color} />
      <circle cx="12" cy="12" r="2" fill={color} />
      <circle cx="19" cy="12" r="2" fill={color} />
    </svg>
  );
}

function StartButton({ team, onPress }) {
  // Single design — large circle. Variants removed from production build.
  const [pressed, setPressed] = useStateH(false);
  const press = (down) => setPressed(down);
  return (
    <button
      onPointerDown={() => press(true)}
      onPointerUp={() => press(false)}
      onPointerLeave={() => press(false)}
      onPointerCancel={() => press(false)}
      onClick={onPress}
      style={{
        width: 290, height: 290, borderRadius: '50%',
        background: team.primary,
        color: team.onPrimary,
        fontFamily: 'var(--display)',
        cursor: 'pointer',
        border: 0,
        display: 'grid',
        placeItems: 'center',
        transform: pressed ? 'scale(0.97)' : 'scale(1)',
        transition: 'transform .12s ease',
        boxShadow: `0 30px 80px -20px ${team.primary}aa, 0 0 0 1px ${team.secondary}33`,
        letterSpacing: '0.02em',
        overflow: 'hidden',
        position: 'relative',
      }}
    >
      <div style={{
        position: 'absolute', inset: 8,
        border: `2px solid ${team.onPrimary}`,
        opacity: 0.18, borderRadius: '50%',
      }} />
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 64, lineHeight: 0.9 }}>START</div>
        <div className="mono" style={{
          fontSize: 11, letterSpacing: '0.3em', marginTop: 8,
          opacity: 0.7, fontFamily: 'var(--mono)',
        }}>
          TAP TO SYNC
        </div>
      </div>
    </button>
  );
}

// Server-synced clock — fetches offset once on mount, then renders local + offset.
function ServerClock() {
  const [offset, setOffset] = useStateH(null);
  const [now, setNow] = useStateH(Date.now());
  useEffectH(() => {
    let alive = true;
    window.TFApi.measureOffset()
      .then((s) => { if (alive) setOffset(s.offset); })
      .catch(() => { if (alive) setOffset(0); });  // fallback: local clock
    const t = setInterval(() => setNow(Date.now()), 100);
    return () => { alive = false; clearInterval(t); };
  }, []);
  if (offset === null) {
    return <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.15em' }}>SERVER · ……</div>;
  }
  const d = new Date(now + offset);
  const hh = d.getHours().toString().padStart(2, '0');
  const mm = d.getMinutes().toString().padStart(2, '0');
  const ss = d.getSeconds().toString().padStart(2, '0');
  const ms = d.getMilliseconds().toString().padStart(3, '0');
  return (
    <div className="mono" style={{
      fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.15em',
    }}>
      SERVER · {hh}:{mm}:{ss}.{ms}
    </div>
  );
}

function ScreenHome({ teamId, onStart, onChangeTeam }) {
  const team = window.findTeam(teamId);
  const [menuOpen, setMenuOpen] = useStateH(false);

  if (!team) {
    return (
      <div className="phone-inner" style={{ background: 'var(--bg)', display: 'grid', placeItems: 'center' }}>
        <div className="mono" style={{ color: 'var(--ink-3)' }}>Loading nation…</div>
      </div>
    );
  }

  return (
    <div className="phone-inner" style={{
      background: 'var(--bg)',
    }}>
      {/* Team-tinted ambient glow */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: `radial-gradient(circle at 50% 70%, ${team.primary}20 0%, transparent 55%),
                     radial-gradient(circle at 50% 10%, ${team.secondary}25 0%, transparent 55%)`,
      }} />

      <StatusBar tone="dark" />
      <div className="island" />

      {/* Top bar */}
      <div style={{
        position: 'absolute', top: 60, left: 24, right: 24,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        zIndex: 2,
      }}>
        <Wordmark size={15} />
        <button onClick={() => setMenuOpen((v) => !v)} style={{
          width: 36, height: 36, borderRadius: 12,
          background: 'var(--bg-2)',
          border: '1px solid var(--line)',
          display: 'grid', placeItems: 'center',
        }}>
          <SettingsIcon color="var(--ink)" />
        </button>
      </div>

      {/* Profile dropdown */}
      {menuOpen && (
        <div style={{
          position: 'absolute', top: 106, right: 24,
          background: 'var(--bg-2)', border: '1px solid var(--line)',
          borderRadius: 14, padding: 6, zIndex: 10,
          width: 180,
          boxShadow: '0 20px 40px -10px rgba(0,0,0,.5)',
        }}>
          {[
            { label: 'Change Nation', cb: () => { setMenuOpen(false); onChangeTeam(); } },
          ].map((it, k) => (
            <button key={k} onClick={it.cb} style={{
              display: 'block', width: '100%', textAlign: 'left',
              padding: '11px 12px', borderRadius: 10,
              fontSize: 14, fontWeight: 600,
              color: it.danger ? 'var(--danger)' : 'var(--ink)',
            }}>
              {it.label}
            </button>
          ))}
        </div>
      )}

      {/* Team identity block */}
      <div style={{
        position: 'absolute', top: 132, left: 24, right: 24,
        zIndex: 2,
      }}>
        <div className="mono" style={{
          fontSize: 10, color: 'var(--ink-3)',
          letterSpacing: '0.25em', marginBottom: 10,
        }}>
          YOUR NATION
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <h2 className="display" style={{
            fontSize: 36, lineHeight: 0.95,
          }}>
            {team.name.toUpperCase()}
          </h2>
          <div style={{ display: 'flex', gap: 4 }}>
            <div style={{ width: 14, height: 28, borderRadius: 3, background: team.primary }} />
            <div style={{ width: 14, height: 28, borderRadius: 3, background: team.secondary, border: /^#?ffffff$/i.test((team.pattern.colors[1] || '').replace('#', '')) ? '1px solid var(--line)' : 'none' }} />
          </div>
        </div>
      </div>

      {/* BIG BUTTON */}
      <div style={{
        position: 'absolute',
        top: 250, bottom: 132, left: 24, right: 24,
        display: 'grid', placeItems: 'center',
        zIndex: 2,
      }}>
        <StartButton team={team} onPress={onStart} />
      </div>

      {/* Footer */}
      <div style={{
        position: 'absolute', bottom: 50, left: 24, right: 24,
        textAlign: 'center', zIndex: 2,
      }}>
        <p style={{
          fontSize: 14, color: 'var(--ink-2)', marginBottom: 8,
          fontWeight: 500,
        }}>
          Join the synchronized fan show.
        </p>
        <ServerClock />
      </div>

      <div className="home-indicator" style={{ color: '#fff' }} />
    </div>
  );
}

window.ScreenHome = ScreenHome;
