// ============================================================
// ELITE COUNTDOWN — Europe/Bucharest, DST-aware
// ------------------------------------------------------------
// States:
//   LIVE     — Mon/Fri, 19:00 ≤ Bucharest time < 21:00
//   COUNT    — countdown to the next Mon/Fri 19:00 Bucharest time
// Re-evaluates every 1s. Pure client; no persistent state.
// ============================================================

const BUCHAREST = 'Europe/Bucharest';

// Returns { y, m, d, dow, hh, mm, ss } in Bucharest local time for a given UTC Date.
// dow: 0=Sun, 1=Mon, ..., 5=Fri, 6=Sat (matching Date.getDay()).
function getBucharestParts(date) {
  const fmt = new Intl.DateTimeFormat('en-US', {
    timeZone: BUCHAREST,
    year: 'numeric', month: '2-digit', day: '2-digit',
    weekday: 'short',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false,
  });
  const parts = fmt.formatToParts(date);
  const map = {};
  for (const p of parts) map[p.type] = p.value;
  const dowMap = { Sun:0, Mon:1, Tue:2, Wed:3, Thu:4, Fri:5, Sat:6 };
  // Some runtimes return "24" for hour at midnight — normalize to "00".
  const hh = map.hour === '24' ? '00' : map.hour;
  return {
    y: +map.year, m: +map.month, d: +map.day,
    dow: dowMap[map.weekday] ?? 0,
    hh: +hh, mm: +map.minute, ss: +map.second,
  };
}

// Compute the UTC instant that corresponds to a given Bucharest wall-clock time.
// Approach: build a UTC Date from the wall-clock fields, then ask what
// Bucharest thinks the time is for that UTC instant; the difference is the
// offset. Apply it. One extra iteration handles DST changeover edge cases.
function bucharestWallClockToUTC(year, month, day, hour, minute = 0, second = 0) {
  // First guess: pretend wall-clock IS UTC, then correct.
  let utc = Date.UTC(year, month - 1, day, hour, minute, second);
  for (let i = 0; i < 2; i++) {
    const p = getBucharestParts(new Date(utc));
    const buchUTC = Date.UTC(p.y, p.m - 1, p.d, p.hh, p.mm, p.ss);
    const delta = buchUTC - utc; // Bucharest wall - UTC = offset (e.g. +7200000 in winter)
    utc = Date.UTC(year, month - 1, day, hour, minute, second) - delta;
  }
  return new Date(utc);
}

// Find the next Mon or Fri at 19:00 Bucharest time strictly AFTER `now`.
function nextCallStart(now) {
  const p = getBucharestParts(now);
  // Start from today in Bucharest local. Iterate up to 8 days.
  for (let offset = 0; offset < 8; offset++) {
    // Compute Bucharest "candidate day" by adding `offset` calendar days to (p.y,p.m,p.d).
    // We do this by constructing a Bucharest wall-clock at 19:00:00 then translating to UTC.
    const candidateUTC = new Date(
      Date.UTC(p.y, p.m - 1, p.d + offset, 19, 0, 0)
    );
    // We need to know the Bucharest weekday for this candidate. Get it via parts.
    const cp = getBucharestParts(candidateUTC);
    // Build the *actual* Bucharest 19:00 UTC instant from cp.y/m/d.
    const startUTC = bucharestWallClockToUTC(cp.y, cp.m, cp.d, 19, 0, 0);
    const endUTC   = bucharestWallClockToUTC(cp.y, cp.m, cp.d, 21, 0, 0);
    if (cp.dow !== 1 && cp.dow !== 5) continue;        // not Mon/Fri
    if (startUTC.getTime() > now.getTime()) {
      return { start: startUTC, end: endUTC };
    }
    // Mon/Fri today but already past 19:00 — only use it if it's still BEFORE 21:00 (live state handles that)
    // Otherwise keep walking.
  }
  // Fallback (should never hit)
  return { start: new Date(now.getTime() + 24*3600*1000), end: new Date(now.getTime() + 26*3600*1000) };
}

// Is `now` inside a live window?
function liveWindow(now) {
  const p = getBucharestParts(now);
  if (p.dow !== 1 && p.dow !== 5) return null;
  // Bucharest 19:00 / 21:00 of TODAY
  const startUTC = bucharestWallClockToUTC(p.y, p.m, p.d, 19, 0, 0);
  const endUTC   = bucharestWallClockToUTC(p.y, p.m, p.d, 21, 0, 0);
  if (now.getTime() >= startUTC.getTime() && now.getTime() < endUTC.getTime()) {
    return { start: startUTC, end: endUTC };
  }
  return null;
}

function fmtCell(n) { return String(Math.max(0, n)).padStart(2, '0'); }

function diffParts(target, now) {
  let ms = Math.max(0, target.getTime() - now.getTime());
  const d = Math.floor(ms / 86400000); ms -= d * 86400000;
  const h = Math.floor(ms / 3600000);  ms -= h * 3600000;
  const m = Math.floor(ms / 60000);    ms -= m * 60000;
  const s = Math.floor(ms / 1000);
  return { d, h, m, s };
}

const EliteCountdown = ({ user, onApply }) => {
  const [now, setNow] = React.useState(() => new Date());

  React.useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);

  const live = liveWindow(now);
  const next = live ? null : nextCallStart(now);
  const parts = next ? diffParts(next.start, now) : null;

  const canJoin = user?.role === 'admin' || user?.role === 'elite';

  return (
    <div className={`elite-countdown ${live ? 'is-live' : ''}`}>
      <div className="elite-countdown-inner">
        {live ? (
          <>
            <div className="ec-head">
              <span className="ec-live-dot"/>
              <span className="ec-eyebrow">ELITE CALL · LIVE NOW</span>
            </div>
            <h3 className="ec-title">We are live now</h3>
            <p className="ec-sub">
              {(getBucharestParts(now).dow === 1 ? 'Luni' : 'Vineri')} · 19:00 – 21:00 RO · NQ Futures
            </p>
            <div style={{marginTop:18}}>
              {canJoin ? (
                <Button variant="acid" icon="arrow">Join Call</Button>
              ) : (
                <Button variant="acid" icon="arrow" onClick={onApply}>Apply for Elite</Button>
              )}
            </div>
          </>
        ) : (
          <>
            <div className="ec-head">
              <span className="ec-dot"/>
              <span className="ec-eyebrow">NEXT ELITE CALL</span>
            </div>
            <h3 className="ec-title">Next Elite Call starts in</h3>
            <div className="ec-grid">
              <div className="ec-cell"><span className="ec-num">{fmtCell(parts.d)}</span><span className="ec-lbl">days</span></div>
              <span className="ec-sep">:</span>
              <div className="ec-cell"><span className="ec-num">{fmtCell(parts.h)}</span><span className="ec-lbl">hours</span></div>
              <span className="ec-sep">:</span>
              <div className="ec-cell"><span className="ec-num">{fmtCell(parts.m)}</span><span className="ec-lbl">min</span></div>
              <span className="ec-sep">:</span>
              <div className="ec-cell"><span className="ec-num">{fmtCell(parts.s)}</span><span className="ec-lbl">sec</span></div>
            </div>
            <p className="ec-sub">
              Bucharest time · Live calls Mon &amp; Fri, 19:00–21:00
            </p>
          </>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { EliteCountdown });
