// ViG Command Center — Event Planner (live countdowns + prep checklists)
const { useState: useStateEV, useEffect: useEffectEV } = React;

/* default event catalogue — dates are editable & saved per device */
const EV_CAT = [
  { id: 'svs', emoji: '⚔️', name: 'Server vs Server', tag: 'PvP', color: '#dc2626', desc: 'The big cross-server war. Coordinate rallies, layers and reinforcements.', prep: ['Fill marches to highest tier', 'Stock speedups & heals', 'Set rally generals + dragons', 'Confirm layer sizes with R4/R5'] },
  { id: 'boc', emoji: '🏛️', name: 'Battle of Constantinople', tag: 'PvP', color: '#9333ea', desc: 'Throne-room control event. Hold the city, rotate rally leads.', prep: ['Assign rally captains', 'Pre-position marches', 'Save teleports'] },
  { id: 'bog', emoji: '🌲', name: 'Battle of Gaul', tag: 'PvP', color: '#16a34a', desc: 'Open-field alliance brawl. Focus-fire and bait traps.', prep: ['Trap-buster march ready', 'Healing speedups', 'Scout enemy keeps'] },
  { id: 'kingspath', emoji: '👑', name: "King's Path", tag: 'Growth', color: '#ca8a04', desc: 'Personal progression event — spend resources for milestone points.', prep: ['Bank RSS for point spikes', 'Hold training & building completions', 'Line up speedups'] },
  { id: 'chalice', emoji: '🏆', name: 'Holy Palace / Chalice', tag: 'Alliance', color: '#FF6B00', desc: 'Alliance occupies the Holy Palace for buffs & ranking.', prep: ['Confirm occupation roster', 'Defensive reinforcements', 'Watch the timer'] },
  { id: 'alliancecomp', emoji: '🛡️', name: 'Alliance Championship', tag: 'Alliance', color: '#2563eb', desc: 'Alliance-wide competition across multiple categories.', prep: ['Push power & kills', 'Coordinate donation pushes', 'Track category leaders'] },
  { id: 'civcup', emoji: '🌍', name: 'Civilization Cup', tag: 'Growth', color: '#0891b2', desc: 'Multi-day growth race with daily and overall rewards.', prep: ['Plan daily point sources', 'Hold completions for double-dip'] },
];

function evDefaultDates() {
  const now = new Date();
  const at = (days, hour) => { const d = new Date(now); d.setDate(d.getDate() + days); d.setHours(hour, 0, 0, 0); return d.getTime(); };
  return { svs: at(5, 12), boc: at(2, 20), bog: at(9, 19), kingspath: at(1, 0), chalice: at(3, 18), alliancecomp: at(14, 0), civcup: at(7, 0) };
}

function evFmtLocal(ts) {
  const d = new Date(ts);
  return d.toISOString().slice(0, 16);
}

function EventCard({ ev, when, now, onEdit }) {
  const [editing, setEditing] = useStateEV(false);
  const diff = when - now;
  const past = diff <= 0;
  const s = Math.abs(Math.floor(diff / 1000));
  const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
  const soon = !past && diff < 24 * 3600 * 1000;
  const units = [[d, 'D'], [h, 'H'], [m, 'M'], [sec, 'S']];

  return (
    <Card className={`relative overflow-hidden p-0 ${soon ? 'ring-1 ring-brand/40' : ''}`}>
      <div className="absolute inset-x-0 top-0 h-1" style={{ background: ev.color }}></div>
      <div className="p-4">
        <div className="flex items-start gap-3">
          <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-[22px]" style={{ background: ev.color + '1c' }}>{ev.emoji}</div>
          <div className="min-w-0 flex-1">
            <div className="flex items-center gap-2">
              <h3 className="truncate text-[15px] font-bold text-zinc-900 dark:text-white">{ev.name}</h3>
              <span className="rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide" style={{ background: ev.color + '22', color: ev.color }}>{ev.tag}</span>
            </div>
            <p className="mt-0.5 line-clamp-2 text-[12px] leading-snug text-zinc-500 dark:text-zinc-400">{ev.desc}</p>
          </div>
          <button onClick={() => setEditing(e => !e)} title="Set date" className="shrink-0 rounded-lg p-1.5 text-zinc-400 hover:bg-zinc-100 hover:text-zinc-600 dark:hover:bg-zinc-800"><Icon name="reset" size={14} /></button>
        </div>

        {/* countdown */}
        <div className="mt-3 flex items-center gap-2">
          {past ? (
            <div className="flex items-center gap-2 rounded-lg bg-zinc-100 px-3 py-2 text-[12.5px] font-semibold text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400"><span className="h-2 w-2 rounded-full bg-zinc-400"></span>Live / passed — update the date</div>
          ) : units.map(([v, l], i) => (
            <div key={l} className="flex flex-col items-center rounded-lg px-2.5 py-1.5" style={{ background: soon ? ev.color + '18' : 'var(--ev-chip)' }}>
              <span className="text-[19px] font-bold leading-none tabular-nums" style={{ color: soon ? ev.color : undefined, fontVariantNumeric: 'tabular-nums' }}>{String(v).padStart(2, '0')}</span>
              <span className="mt-0.5 text-[9px] font-semibold uppercase tracking-wider text-zinc-400">{l}</span>
            </div>
          ))}
        </div>

        {editing && (
          <div className="mt-3 flex items-center gap-2 rounded-lg border border-zinc-200 p-2 dark:border-zinc-700">
            <input type="datetime-local" defaultValue={evFmtLocal(when)} onChange={e => { const t = new Date(e.target.value).getTime(); if (!isNaN(t)) onEdit(ev.id, t); }}
              className="flex-1 bg-transparent text-[12.5px] outline-none" />
            <button onClick={() => setEditing(false)} className="rounded-md bg-brand px-2.5 py-1 text-[11.5px] font-semibold text-white">Done</button>
          </div>
        )}

        {/* prep checklist */}
        <details className="mt-3 group">
          <summary className="flex cursor-pointer list-none items-center gap-1.5 text-[11.5px] font-semibold text-zinc-500 hover:text-brand dark:text-zinc-400"><Icon name="check" size={13} />Prep checklist ({ev.prep.length})</summary>
          <ul className="mt-2 space-y-1">
            {ev.prep.map((p, i) => <li key={i} className="flex items-start gap-2 text-[12px] text-zinc-600 dark:text-zinc-300"><span className="mt-1.5 h-1 w-1 rounded-full" style={{ background: ev.color }}></span>{p}</li>)}
          </ul>
        </details>
      </div>
    </Card>
  );
}

function EventsPage() {
  const [dates, setDates] = useStateEV(() => ({ ...evDefaultDates(), ...LS.get('vig2_events', {}) }));
  const [now, setNow] = useStateEV(Date.now());
  const [filter, setFilter] = useStateEV('All');
  useEffectEV(() => { const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, []);
  const edit = (id, ts) => setDates(d => { const n = { ...d, [id]: ts }; LS.set('vig2_events', n); return n; });

  const TAGS = ['All', 'PvP', 'Growth', 'Alliance'];
  const list = EV_CAT.filter(e => filter === 'All' || e.tag === filter)
    .map(e => ({ ev: e, when: dates[e.id] }))
    .sort((a, b) => { const ap = a.when - now, bp = b.when - now; if (ap > 0 && bp <= 0) return -1; if (bp > 0 && ap <= 0) return 1; return ap - bp; });

  const next = list.find(x => x.when - now > 0);

  return (
    <div className="space-y-4">
      <style>{`:root{--ev-chip:#f4f4f5;} html.dark{--ev-chip:#19213a;}`}</style>

      {/* next-up hero */}
      {next && (
        <Card className="relative overflow-hidden p-5" style={{ background: `linear-gradient(110deg, ${next.ev.color}14, transparent 70%)` }}>
          <div className="flex flex-wrap items-center gap-4">
            <div className="flex h-14 w-14 items-center justify-center rounded-2xl text-[28px]" style={{ background: next.ev.color + '22' }}>{next.ev.emoji}</div>
            <div className="min-w-0 flex-1">
              <div className="text-[11px] font-bold uppercase tracking-wider" style={{ color: next.ev.color }}>Next up</div>
              <div className="text-[19px] font-bold text-zinc-900 dark:text-white">{next.ev.name}</div>
              <div className="text-[12.5px] text-zinc-500 dark:text-zinc-400">{new Date(next.when).toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</div>
            </div>
            <div className="text-right">
              {(() => { const s = Math.max(0, Math.floor((next.when - now) / 1000)); const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60); return (
                <div className="text-[30px] font-bold tabular-nums leading-none" style={{ color: next.ev.color }}>{d > 0 ? `${d}d ${h}h` : `${h}h ${m}m`}</div>
              ); })()}
              <div className="mt-1 text-[11px] uppercase tracking-wide text-zinc-400">until start</div>
            </div>
          </div>
        </Card>
      )}

      <div className="flex items-center gap-1.5">
        {TAGS.map(t => (
          <button key={t} onClick={() => setFilter(t)} className={`rounded-lg border px-3 py-1.5 text-[12.5px] font-semibold transition-colors ${filter === t ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-500 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-400 dark:hover:bg-zinc-800'}`}>{t}</button>
        ))}
        <span className="ml-auto text-[11.5px] text-zinc-400">Tap the clock icon on a card to set its date for your server.</span>
      </div>

      <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
        {list.map(x => <EventCard key={x.ev.id} ev={x.ev} when={x.when} now={now} onEdit={edit} />)}
      </div>

      <p className="px-1 text-[11.5px] text-zinc-400">Event timing varies by server and season — set each event's date to match your kingdom's schedule. Countdowns update live and your dates save on this device.</p>
    </div>
  );
}
window.EventsPage = EventsPage;
