/* ui.jsx — shared low-level UI primitives. Babel JSX. */

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

// ── Logo ────────────────────────────────────────────────────────────────────
function TriniumMark({ size = 14, accent = '#10B981' }) {
  // emerald dot + wordmark in spaced tracking
  return (
    <span className="inline-flex items-center gap-2.5 leading-none select-none">
      <span
        className="rounded-full em-pulse"
        style={{
          width: size, height: size,
          background: accent,
          boxShadow: `0 0 0 ${size * 0.25}px rgba(16,185,129,0.18)`,
        }}
      />
      <span
        className="font-sans font-bold tracking-[0.32em]"
        style={{ fontSize: size + 1, letterSpacing: '0.32em' }}
      >
        TRINIUM
      </span>
    </span>
  );
}

// ── Tag pill (used by [BTC-USD][5MIN][UP/DOWN]) ─────────────────────────────
function Tag({ children, tone = 'neutral' }) {
  const tones = {
    neutral: 'text-text border-line-3 bg-bg-2',
    emerald: 'text-emerald border-emerald/40 bg-emerald/[0.08]',
    amber:   'text-amber  border-amber/40   bg-amber/[0.06]',
  };
  return (
    <span className={`inline-flex items-center h-[22px] px-2 border ${tones[tone]} font-mono text-[10px] tracking-[0.14em] uppercase`}>
      {children}
    </span>
  );
}

// ── Section frame with a 10px caps label in the corner ──────────────────────
function PaneTitle({ children, right }) {
  return (
    <div className="h-[28px] px-3 flex items-center justify-between hl-b">
      <span className="font-mono text-[10px] tracking-[0.18em] uppercase text-text-2">{children}</span>
      {right && <span className="font-mono text-[10px] tracking-[0.10em] uppercase text-text-3">{right}</span>}
    </div>
  );
}

// ── KV pair displayed inline (used in market header, position strip) ────────
function KV({ k, v, tone = 'neutral', mono = true }) {
  const tones = {
    neutral: 'text-text',
    green: 'text-green',
    red: 'text-red',
    amber: 'text-amber',
    emerald: 'text-emerald',
    muted: 'text-text-2',
  };
  return (
    <div className="flex flex-col gap-[3px]">
      <span className="font-mono text-[9.5px] tracking-[0.18em] uppercase text-text-3">{k}</span>
      <span className={`${mono ? 'font-mono' : 'font-sans'} text-[13px] leading-none ${tones[tone]}`}>{v}</span>
    </div>
  );
}

// ── Inline segmented control ────────────────────────────────────────────────
function Segmented({ options, value, onChange, size = 'sm' }) {
  const h = size === 'sm' ? 'h-[26px]' : 'h-[30px]';
  return (
    <div className={`inline-flex ${h} border border-line-3 bg-bg-2`}>
      {options.map((o, i) => {
        const active = (typeof o === 'string' ? o : o.value) === value;
        const label = typeof o === 'string' ? o : o.label;
        const val   = typeof o === 'string' ? o : o.value;
        return (
          <button
            key={val}
            onClick={() => onChange(val)}
            className={[
              'px-2.5 font-mono text-[10.5px] tracking-[0.12em] uppercase transition-colors',
              i > 0 ? 'border-l border-line-3' : '',
              active ? 'bg-bg-hover text-text' : 'text-text-2 hover:text-text hover:bg-bg-3'
            ].join(' ')}
          >{label}</button>
        );
      })}
    </div>
  );
}

// ── Live clock (UTC, updates every second) ──────────────────────────────────
function useClock() {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  return now;
}

function utcClock(d) {
  const hh = String(d.getUTCHours()).padStart(2, '0');
  const mm = String(d.getUTCMinutes()).padStart(2, '0');
  const ss = String(d.getUTCSeconds()).padStart(2, '0');
  return `${hh}:${mm}:${ss}`;
}

// ── Countdown to next 5-minute boundary ─────────────────────────────────────
function useMarketCountdown() {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const now = new Date();
  // Next 5-min boundary in UTC
  const minutes = now.getUTCMinutes();
  const nextBoundaryMin = Math.ceil((minutes + 1) / 5) * 5; // always ≥ next slot
  const boundary = new Date(now);
  boundary.setUTCSeconds(0, 0);
  boundary.setUTCMinutes(nextBoundaryMin);
  if (boundary <= now) boundary.setUTCMinutes(boundary.getUTCMinutes() + 5);
  const secs = Math.max(0, Math.floor((boundary.getTime() - now.getTime()) / 1000));
  const mm = String(Math.floor(secs / 60)).padStart(2, '0');
  const ss = String(secs % 60).padStart(2, '0');
  const hh = String(boundary.getUTCHours()).padStart(2, '0');
  const bm = String(boundary.getUTCMinutes()).padStart(2, '0');
  return { secs, label: `${mm}:${ss}`, resolveLabel: `${hh}:${bm}`, resolveAt: boundary };
}

// ── Countdown that loops to 05:00 when it hits zero ─────────────────────────
function useCountdown(initialSecs = 222) {
  const [secs, setSecs] = useState(initialSecs);
  useEffect(() => {
    const id = setInterval(() => {
      setSecs(s => (s <= 1 ? 300 : s - 1));
    }, 1000);
    return () => clearInterval(id);
  }, []);
  const mm = String(Math.floor(secs / 60)).padStart(2, '0');
  const ss = String(secs % 60).padStart(2, '0');
  return { secs, label: `${mm}:${ss}` };
}

Object.assign(window, { TriniumMark, Tag, PaneTitle, KV, Segmented, useClock, utcClock, useCountdown, useMarketCountdown });
