// ViG Command Center — Discord integration (client-side webhook posting, CORS-enabled)
const { useState: useStateDC, useEffect: useEffectDC } = React;

const DC_CFG_KEY = 'vig2_discord_cfg';
const DC_TRIGGERS = [
  ['briefing', 'Daily AI briefing', 'Post the auto-generated 3-point briefing each day'],
  ['alerts', 'Smart alerts', 'Covenants ready, alliance moves, imminent events'],
  ['events', 'Event reminders', 'Ping when a tracked event is within 24h'],
  ['digest', 'Weekly digest', 'A summary of roster & alliance progress each week'],
];

function dcCfg() { return LS.get(DC_CFG_KEY, { url: '', name: 'ViG Command Center', on: { briefing: true, alerts: true, events: true, digest: false }, lastSent: {} }); }
function dcSave(c) { LS.set(DC_CFG_KEY, c); }

async function dcPost(url, payload) {
  if (!url) throw new Error('No webhook URL');
  const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
  if (!res.ok && res.status !== 204) throw new Error('Discord returned ' + res.status);
  return true;
}

/* build a rich embed from current data */
function dcBuildEmbed(kind) {
  const orange = 0xFF6B00, cyan = 0x22D3EE, purple = 0xA855F7;
  if (kind === 'briefing') {
    const b = LS.get('vig2_ai_brief', null);
    if (!b) return null;
    const lines = b.text.split('\n').map(l => l.replace(/^[-*•]\s*/, '').trim()).filter(Boolean).slice(0, 4);
    return { title: '📋 Daily Briefing', color: orange, description: lines.map((l, i) => `**${i + 1}.** ${l.replace(/\*\*/g, '**')}`).join('\n'), footer: { text: 'ViG Command Center' }, timestamp: new Date().toISOString() };
  }
  if (kind === 'alerts') {
    const al = (window.computeAlerts ? window.computeAlerts() : []).slice(0, 5);
    if (!al.length) return null;
    return { title: '🔔 Smart Alerts', color: cyan, fields: al.map(a => ({ name: a.title, value: a.body || '\u200b' })), footer: { text: 'ViG Command Center' }, timestamp: new Date().toISOString() };
  }
  if (kind === 'digest') {
    const V = window.VIG, own = LS.get('vig2_ownership', {}) || {};
    const owned = (V?.generals || []).filter(g => own[g.type + '|' + g.name]).length;
    let covLine = '—';
    try { const ownedByName = n => (V?.generals || []).some(g => g.name === n && own[g.type + '|' + g.name]); covLine = String(V.covenants.filter(c => window.CALC.covenantStatus(c, ownedByName).complete).length); } catch (e) {}
    let allianceLine = '—';
    try { const a = (window.ALLIANCE?.alliances || []).find(x => x.id === 'VIG'); if (a) allianceLine = `${a.power.toFixed(0)}B · ${a.memberCount || a.players.length} members`; } catch (e) {}
    return { title: '📊 Weekly Digest', color: purple, fields: [
      { name: 'Generals owned', value: `${owned}/${(V?.generals || []).length}`, inline: true },
      { name: 'Covenants complete', value: covLine, inline: true },
      { name: 'VIG alliance', value: allianceLine, inline: true },
    ], footer: { text: 'ViG Command Center' }, timestamp: new Date().toISOString() };
  }
  return null;
}

/* auto-post on load: send each enabled trigger at most once per day */
async function dcAutoPost() {
  const c = dcCfg();
  if (!c.url) return;
  const today = new Date().toISOString().slice(0, 10);
  const week = (() => { const d = new Date(); return d.getFullYear() + '-W' + Math.ceil(((d - new Date(d.getFullYear(), 0, 1)) / 86400000 + 1) / 7); })();
  const sent = { ...(c.lastSent || {}) };
  let changed = false;
  for (const k of ['briefing', 'alerts']) {
    if (c.on[k] && sent[k] !== today) {
      const e = dcBuildEmbed(k);
      if (e) { try { await dcPost(c.url, { username: c.name, embeds: [e] }); sent[k] = today; changed = true; } catch (err) {} }
    }
  }
  if (c.on.digest && sent.digest !== week) {
    const e = dcBuildEmbed('digest');
    if (e) { try { await dcPost(c.url, { username: c.name, embeds: [e] }); sent.digest = week; changed = true; } catch (err) {} }
  }
  if (changed) dcSave({ ...c, lastSent: sent });
}
window.dcAutoPost = dcAutoPost;

function DiscordPage() {
  const [cfg, setCfg] = useStateDC(dcCfg);
  const [status, setStatus] = useStateDC(null);
  const [busy, setBusy] = useStateDC('');
  const save = patch => { const n = { ...cfg, ...patch }; setCfg(n); dcSave(n); };
  const toggle = k => save({ on: { ...cfg.on, [k]: !cfg.on[k] } });

  const valid = /^https:\/\/(discord|discordapp)\.com\/api\/webhooks\//.test(cfg.url.trim());

  const sendTest = async () => {
    setBusy('test'); setStatus(null);
    try {
      await dcPost(cfg.url.trim(), { username: cfg.name || 'ViG Command Center', embeds: [{ title: '✅ Connected', description: 'ViG Command Center is now linked to this channel. Automated updates will post here.', color: 0xFF6B00, footer: { text: 'ViG Command Center' }, timestamp: new Date().toISOString() }] });
      setStatus({ ok: true, msg: 'Test message sent — check your Discord channel.' });
    } catch (e) { setStatus({ ok: false, msg: 'Failed: ' + e.message + '. Check the webhook URL is correct and complete.' }); }
    finally { setBusy(''); }
  };
  const sendNow = async (kind) => {
    setBusy(kind); setStatus(null);
    const e = dcBuildEmbed(kind);
    if (!e) { setStatus({ ok: false, msg: kind === 'briefing' ? 'No briefing yet — open the Command Center first to generate one.' : 'Nothing to send right now.' }); setBusy(''); return; }
    try { await dcPost(cfg.url.trim(), { username: cfg.name || 'ViG Command Center', embeds: [e] }); setStatus({ ok: true, msg: 'Posted to Discord.' }); }
    catch (er) { setStatus({ ok: false, msg: 'Failed: ' + er.message }); }
    finally { setBusy(''); }
  };

  const inp = 'h-11 w-full rounded-lg border border-zinc-200 bg-white px-3 text-[13px] outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900';

  return (
    <div className="mx-auto max-w-2xl space-y-4">
      {/* connect */}
      <Card className="overflow-hidden">
        <div className="flex items-center gap-3 border-b border-zinc-100 px-4 py-3.5 dark:border-zinc-800">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl text-[20px]" style={{ background: '#5865F2' }}>💬</div>
          <div>
            <h3 className="text-[14px] font-bold text-zinc-900 dark:text-white">Discord integration</h3>
            <p className="text-[11.5px] text-zinc-400">Auto-post briefings, alerts &amp; digests to your alliance channel</p>
          </div>
          {valid && <span className="ml-auto flex items-center gap-1.5 rounded-full bg-emerald-500/15 px-2.5 py-1 text-[11px] font-bold text-emerald-500"><span className="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>Connected</span>}
        </div>
        <div className="space-y-3 p-4">
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Webhook URL</label>
            <input value={cfg.url} onChange={e => save({ url: e.target.value })} placeholder="https://discord.com/api/webhooks/…" className={inp + ' font-mono text-[12px]'} />
            <p className="mt-1.5 text-[11px] text-zinc-400">In Discord: <b>Server Settings → Integrations → Webhooks → New Webhook → Copy URL</b>. Paste it here — it stays on your device.</p>
          </div>
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Bot display name</label>
            <input value={cfg.name} onChange={e => save({ name: e.target.value })} className={inp} />
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <button onClick={sendTest} disabled={!valid || busy} className="inline-flex items-center gap-1.5 rounded-lg px-3.5 py-2 text-[12.5px] font-semibold text-white transition-all hover:brightness-110 disabled:opacity-40" style={{ background: '#5865F2' }}>
              <Icon name={busy === 'test' ? 'reset' : 'check'} size={14} className={busy === 'test' ? 'animate-spin' : ''} />Send test message
            </button>
            {!valid && cfg.url && <span className="text-[11.5px] text-amber-500">That doesn't look like a Discord webhook URL.</span>}
          </div>
          {status && <div className={`rounded-lg px-3 py-2 text-[12px] ${status.ok ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300' : 'bg-rose-50 text-rose-600 dark:bg-rose-950/40 dark:text-rose-300'}`}>{status.msg}</div>}
        </div>
      </Card>

      {/* triggers */}
      <Card className="overflow-hidden">
        <div className="border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
          <h3 className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Automated posts</h3>
          <p className="text-[11.5px] text-zinc-400">Each fires automatically at most once per day (digest: weekly) when you open the app</p>
        </div>
        <div className="divide-y divide-zinc-50 dark:divide-zinc-800/60">
          {DC_TRIGGERS.map(([k, label, desc]) => (
            <div key={k} className="flex items-center gap-3 px-4 py-3">
              <div className="min-w-0 flex-1">
                <div className="text-[13px] font-semibold text-zinc-900 dark:text-white">{label}</div>
                <div className="text-[11.5px] text-zinc-400">{desc}</div>
              </div>
              {(k === 'briefing' || k === 'alerts' || k === 'digest') && valid && (
                <button onClick={() => sendNow(k)} disabled={busy} className="rounded-lg border border-zinc-200 px-2.5 py-1.5 text-[11.5px] font-semibold text-zinc-500 hover:border-brand hover:text-brand disabled:opacity-40 dark:border-zinc-700 dark:text-zinc-400">{busy === k ? 'Sending…' : 'Post now'}</button>
              )}
              <button onClick={() => toggle(k)} className="relative h-5 w-9 shrink-0 rounded-full transition-colors" style={{ background: cfg.on[k] ? '#FF6B00' : '#9ca3af' }}><span className="absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all" style={{ left: cfg.on[k] ? 16 : 2 }}></span></button>
            </div>
          ))}
        </div>
      </Card>

      <p className="px-1 text-[11.5px] text-zinc-400">Posts are sent straight from your browser to Discord's webhook — no server involved, and the URL never leaves your device. For posts that fire even when nobody has the app open, move the webhook call into the included Cloudflare Worker's daily cron.</p>
    </div>
  );
}
window.DiscordPage = DiscordPage;
