/* global React, Icon */
const { useEffect } = React;

/* ============== Active events bar ============== */
function EventsBar({ events, now }) {
  if (events.length === 0) return null;
  return (
    <div className="events-bar" role="list" aria-label="Active event buffs">
      {events.map((ev) => {
        const remaining = Math.max(0, (ev.expiresAt - now) / 1000);
        const pct = Math.max(0, Math.min(100, (remaining / ev.def.duration) * 100));
        const Ico = Icon[ev.def.icon] || Icon.sparkle;
        return (
          <div key={ev.uid} className={`event-chip event-${ev.def.color}`} role="listitem">
            <div className="event-chip-ico" aria-hidden="true">{Ico(16)}</div>
            <div className="event-chip-mid">
              <div className="event-chip-row">
                <span className="event-chip-name">{ev.def.name}</span>
                <span className="event-chip-time" aria-label={`${remaining.toFixed(1)} seconds remaining`}>{remaining.toFixed(1)}s</span>
              </div>
              <div className="event-chip-desc">{ev.def.desc}</div>
              <div
                className="event-chip-bar"
                role="progressbar"
                aria-valuenow={Math.round(pct)}
                aria-valuemin={0}
                aria-valuemax={100}
                aria-label={`${ev.def.name} time remaining`}
              >
                <div className="event-chip-fill" style={{ width: `${pct}%` }} />
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ============== Click-to-claim popup ============== */
function EventPopup({ pending, now, onClaim, onDismiss }) {
  useEffect(() => {
    if (!pending) return;
    const fn = (e) => { if (e.key === "Escape") onDismiss(); };
    document.addEventListener("keydown", fn);
    return () => document.removeEventListener("keydown", fn);
  }, [pending, onDismiss]);

  if (!pending) return null;
  const remaining = Math.max(0, (pending.expiresAt - now) / 1000);
  const pct = Math.max(0, Math.min(100, (remaining / pending.def.duration) * 100));
  const Ico = Icon[pending.def.icon] || Icon.star;
  return (
    <div
      className={`event-popup event-${pending.def.color}`}
      onClick={onClaim}
      role="dialog"
      aria-modal="true"
      aria-labelledby="event-popup-label"
      aria-describedby="event-popup-desc"
    >
      <button
        className="event-popup-close"
        onClick={(e) => { e.stopPropagation(); onDismiss(); }}
        aria-label="Dismiss event"
      >×</button>
      <div className="event-popup-burst" aria-hidden="true" />
      <div className="event-popup-ico" aria-hidden="true">{Ico(34)}</div>
      <div className="event-popup-name" id="event-popup-label">{pending.def.name}</div>
      <div className="event-popup-desc" id="event-popup-desc">{pending.def.desc}</div>
      <div className="event-popup-cta" aria-hidden="true">CLAIM</div>
      <div
        className="event-popup-bar"
        role="progressbar"
        aria-valuenow={Math.round(pct)}
        aria-valuemin={0}
        aria-valuemax={100}
        aria-label="Time remaining to claim"
      >
        <div className="event-popup-fill" style={{ width: `${pct}%` }} />
      </div>
      <div className="event-popup-timer" aria-live="off">{remaining.toFixed(1)}s left</div>
    </div>
  );
}

/* ============== Debug menu ============== */
function DebugPanel({ open, onClose, onSpawn, eventsDefs, onGivePP, onGiveSP, onLevelUp, onMaxAll, onReset, onResetDaily, gachaTiers, gachaForcedTier, onForceGacha }) {
  useEffect(() => {
    if (!open) return;
    const fn = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", fn);
    return () => document.removeEventListener("keydown", fn);
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div className="debug-veil" onClick={onClose} aria-hidden="true">
      <div
        className="debug-panel"
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="debug-panel-title"
      >
        <div className="debug-head">
          <div>
            <div className="debug-eyebrow">Developer</div>
            <div className="debug-title" id="debug-panel-title">Debug Menu</div>
            <div className="debug-sub">Summon events on demand and apply test cheats.</div>
          </div>
          <button className="debug-close" onClick={onClose} aria-label="close">×</button>
        </div>

        <div className="debug-section">
          <div className="debug-section-title">
            <span>Summon Event</span>
            <span className="debug-pill">{eventsDefs.length}</span>
          </div>
          <div className="debug-grid">
            {eventsDefs.map((def) => {
              const Ico = Icon[def.icon] || Icon.sparkle;
              const typeLabel =
                def.type === "buff"    ? `BUFF · ${def.duration}s`
              : def.type === "click"   ? `CLICK · ${def.duration}s`
              :                          "INSTANT";
              return (
                <button
                  key={def.id}
                  className={`debug-event-btn event-${def.color}`}
                  onClick={() => onSpawn(def.id)}
                >
                  <span className="debug-event-ico">{Ico(18)}</span>
                  <span className="debug-event-text">
                    <span className="debug-event-name">{def.name}</span>
                    <span className="debug-event-desc">{def.desc}</span>
                  </span>
                  <span className="debug-event-tag">{typeLabel}</span>
                </button>
              );
            })}
          </div>
        </div>

        {gachaTiers && onForceGacha && (
          <div className="debug-section">
            <div className="debug-section-title">
              <span>Force next gacha</span>
              {gachaForcedTier != null && (
                <span className="debug-pill" style={{ background: "var(--pink)", color: "#fff" }}>
                  {gachaForcedTier}★ queued
                </span>
              )}
            </div>
            <div className="debug-gacha-grid">
              {gachaTiers.map((t) => (
                <button
                  key={t.stars}
                  className={`debug-tier-btn ${gachaForcedTier === t.stars ? "active" : ""}`}
                  onClick={() => onForceGacha(t.stars)}
                  style={{
                    borderColor: t.color,
                    background: gachaForcedTier === t.stars
                      ? `linear-gradient(135deg, ${t.color}, ${t.glow})`
                      : undefined,
                    color: gachaForcedTier === t.stars ? "#fff" : t.color,
                  }}
                  title={t.name}
                >
                  <span className="debug-tier-stars">{t.stars}★</span>
                  <span className="debug-tier-name">{t.name}</span>
                </button>
              ))}
              <button
                className="debug-tier-btn debug-tier-clear"
                onClick={() => onForceGacha(null)}
                disabled={gachaForcedTier == null}
              >
                <span className="debug-tier-stars">↺</span>
                <span className="debug-tier-name">Random</span>
              </button>
            </div>
          </div>
        )}

        <div className="debug-section">
          <div className="debug-section-title"><span>Cheats</span></div>
          <div className="debug-cheats">
            <button className="debug-btn" onClick={() => onGivePP(1000)}>+1K PP</button>
            <button className="debug-btn" onClick={() => onGivePP(100000)}>+100K PP</button>
            <button className="debug-btn" onClick={() => onGivePP(10_000_000)}>+10M PP</button>
            <button className="debug-btn" onClick={() => onGivePP(1_000_000_000)}>+1B PP</button>
            <button className="debug-btn" onClick={() => onGiveSP(5)}>+5 SP</button>
            <button className="debug-btn" onClick={onLevelUp}>+1 Level</button>
            <button className="debug-btn" onClick={onMaxAll}>Max all skills</button>
            {onResetDaily && (
              <button className="debug-btn" onClick={onResetDaily}>Reset daily pull</button>
            )}
            <button className="debug-btn danger" onClick={onReset}>Reset state</button>
          </div>
        </div>

        <div className="debug-foot">
          Tip: events stack — try Lucky Streak + Tournament + Critical Hour together.
        </div>
      </div>
    </div>
  );
}

window.EventsBar = EventsBar;
window.EventPopup = EventPopup;
window.DebugPanel = DebugPanel;
