// ViG Command Center — AI Assistant (live model, grounded in the user's own data)
const { useState: useStateAI, useEffect: useEffectAI, useRef: useRefAI } = React;

/* ---- build a compact context summary of the player's current state ---- */
function buildAIContext() {
  const V = window.VIG || { generals: [], covenants: [] };
  const own = (window.LS && LS.get('vig2_ownership', {})) || {};
  const roleOwn = (window.LS && LS.get('vig2_role_owned', {})) || {};
  const ownKey = g => g.type + '|' + g.name;
  const ownedByName = name => V.generals.some(g => g.name === name && own[ownKey(g)]) || !!roleOwn[name];

  const TYPES = ['Ground', 'Mounted', 'Ranged', 'Siege'];
  const byType = TYPES.map(t => {
    const arr = V.generals.filter(g => g.type === t);
    return `${t}: ${arr.filter(g => own[ownKey(g)]).length}/${arr.length}`;
  }).join(', ');
  const ownedGens = V.generals.filter(g => own[ownKey(g)]);
  const topOwned = ownedGens.slice().sort((a, b) => (b.totAtk || 0) - (a.totAtk || 0)).slice(0, 12).map(g => g.name);

  let covLine = '', nextCov = '';
  try {
    const covs = V.covenants.map(c => window.CALC.covenantStatus(c, ownedByName));
    const complete = covs.filter(c => c.complete).length;
    const partial = covs.filter(c => !c.complete && c.ownedCount > 0).length;
    covLine = `${complete} complete, ${partial} in progress, of ${V.covenants.length} total`;
    const picks = window.CALC.optimizeCovenants(ownedByName, 4) || [];
    nextCov = picks.map(p => `${p.cov.main} (needs ${p.missing.join(', ')})`).join('; ');
  } catch (e) {}

  let alliance = '';
  try {
    const A = window.ALLIANCE;
    if (A && A.alliances) {
      alliance = A.alliances.slice().sort((a, b) => b.power - a.power)
        .map(a => `${a.id} ${(a.power).toFixed(0)}B power, ${a.memberCount || a.players.length} members`).join(' | ');
    }
  } catch (e) {}

  return [
    `PLAYER ACCOUNT SNAPSHOT (live from this app):`,
    `- Generals owned by troop type: ${byType}`,
    `- Total owned: ${ownedGens.length}/${V.generals.length}`,
    topOwned.length ? `- Strongest owned generals: ${topOwned.join(', ')}` : `- No generals marked owned yet.`,
    covLine ? `- Covenants: ${covLine}` : '',
    nextCov ? `- Best covenants to finish next: ${nextCov}` : '',
    alliance ? `- Alliance standings: ${alliance}` : '',
  ].filter(Boolean).join('\n');
}

const AI_SYS = `You are the ViG Command Center AI — an expert assistant for the mobile strategy game Evony: The King's Return, embedded in an alliance management app for the alliance "ViG".
Help with generals, covenants, dragons, troop tiers, marches/rallies, buffs, construction, academy research and alliance strategy.
Use the player's account snapshot below to give specific, personalized advice — reference their owned generals, covenant progress and alliance position when relevant.
Be concise and practical: short paragraphs or tight bullet lists, concrete numbers, no fluff. If asked something the snapshot can't answer, give solid general Evony guidance and say what the player should check in the app.`;

const AI_SUGGESTIONS = [
  'Which covenant should I finish next and why?',
  'What troop tier mix should I rally with?',
  'How do I maximize research speed?',
  'Who are my strongest generals and how should I use them?',
  'How is ViG doing vs RSP and NEF right now?',
  'What should I prioritize to grow my account fastest?',
];

const AI_KEY = 'vig2_ai_chat';

function AIAssistantPage() {
  const [msgs, setMsgs] = useStateAI(() => LS.get(AI_KEY, []));
  const [input, setInput] = useStateAI('');
  const [busy, setBusy] = useStateAI(false);
  const [err, setErr] = useStateAI('');
  const scrollRef = useRefAI(null);
  useEffectAI(() => { LS.set(AI_KEY, msgs.slice(-40)); }, [msgs]);
  useEffectAI(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [msgs, busy]);

  const send = async (text) => {
    const q = (text != null ? text : input).trim();
    if (!q || busy) return;
    setInput(''); setErr('');
    const next = [...msgs, { role: 'user', content: q }];
    setMsgs(next); setBusy(true);
    try {
      const convo = next.slice(-8).map(m => `${m.role === 'user' ? 'Player' : 'Assistant'}: ${m.content}`).join('\n\n');
      const prompt = `${AI_SYS}\n\n${buildAIContext()}\n\nCONVERSATION:\n${convo}\n\nAssistant:`;
      const reply = await window.claude.complete(prompt);
      setMsgs(m => [...m, { role: 'assistant', content: (reply || '').trim() || 'Sorry — I could not generate a response. Try again.' }]);
    } catch (e) {
      setErr('The AI is unavailable right now. It needs an internet connection and may be rate-limited — try again in a moment.');
      setMsgs(m => m.slice(0, -1).concat({ role: 'user', content: q, failed: true }));
    } finally { setBusy(false); }
  };

  const fmt = (s) => s.split('\n').map((line, i) => {
    const t = line.trim();
    if (!t) return <div key={i} className="h-1.5"></div>;
    const bullet = /^[-*•]\s+/.test(t);
    const num = /^\d+[.)]\s+/.test(t);
    const body = t.replace(/^[-*•]\s+/, '').replace(/^\d+[.)]\s+/, '');
    const parts = body.split(/(\*\*[^*]+\*\*)/g).map((p, j) => p.startsWith('**') && p.endsWith('**')
      ? <strong key={j} className="font-semibold text-zinc-900 dark:text-white">{p.slice(2, -2)}</strong> : p);
    if (bullet || num) return <div key={i} className="flex gap-2 py-0.5"><span className="mt-1.5 shrink-0 text-brand">{num ? t.match(/^\d+/)[0] + '.' : '•'}</span><span>{parts}</span></div>;
    return <p key={i} className="py-0.5">{parts}</p>;
  });

  return (
    <div className="mx-auto flex h-[calc(100vh-128px)] max-w-3xl flex-col">
      {msgs.length === 0 ? (
        <div className="flex flex-1 flex-col items-center justify-center px-4 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)', boxShadow: '0 16px 44px -12px rgba(255,107,0,.7)' }}>
            <Icon name="sparkle" size={32} className="text-white" />
          </div>
          <h2 className="mt-4 text-[22px] font-bold tracking-tight text-zinc-900 dark:text-white">ViG AI Assistant</h2>
          <p className="mt-1.5 max-w-md text-[13.5px] leading-relaxed text-zinc-500 dark:text-zinc-400">Ask anything about your generals, covenants, dragons, marches or alliance. I read your live account data to answer.</p>
          <div className="mt-6 grid w-full max-w-xl grid-cols-1 gap-2 sm:grid-cols-2">
            {AI_SUGGESTIONS.map(s => (
              <button key={s} onClick={() => send(s)} className="rounded-xl border border-zinc-200 bg-white px-3.5 py-2.5 text-left text-[12.5px] font-medium text-zinc-600 transition-all hover:border-brand hover:text-brand dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-300">{s}</button>
            ))}
          </div>
        </div>
      ) : (
        <div ref={scrollRef} className="flex-1 space-y-4 overflow-y-auto px-1 py-2">
          {msgs.map((m, i) => (
            <div key={i} className={`flex gap-3 ${m.role === 'user' ? 'justify-end' : ''}`}>
              {m.role === 'assistant' && <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}><Icon name="sparkle" size={16} className="text-white" /></div>}
              <div className={`max-w-[78%] rounded-2xl px-4 py-2.5 text-[13.5px] leading-relaxed ${m.role === 'user' ? 'bg-brand text-white' : 'bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-200'} ${m.failed ? 'opacity-50' : ''}`}>
                {m.role === 'assistant' ? <div>{fmt(m.content)}</div> : m.content}
              </div>
            </div>
          ))}
          {busy && (
            <div className="flex gap-3">
              <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}><Icon name="sparkle" size={16} className="text-white" /></div>
              <div className="flex items-center gap-1 rounded-2xl bg-zinc-100 px-4 py-3.5 dark:bg-zinc-800">
                <span className="ai-dot"></span><span className="ai-dot" style={{ animationDelay: '.15s' }}></span><span className="ai-dot" style={{ animationDelay: '.3s' }}></span>
              </div>
            </div>
          )}
        </div>
      )}

      {err && <div className="mb-2 rounded-lg bg-rose-50 px-3 py-2 text-[12px] text-rose-600 dark:bg-rose-950/40 dark:text-rose-300">{err}</div>}

      <div className="mt-2">
        <div className="flex items-end gap-2 rounded-2xl border border-zinc-200 bg-white p-2 shadow-sm focus-within:border-brand dark:border-zinc-700 dark:bg-zinc-900">
          <textarea value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
            rows={1} placeholder="Ask the ViG AI…" className="max-h-32 flex-1 resize-none bg-transparent px-2 py-1.5 text-[13.5px] outline-none placeholder:text-zinc-400" style={{ minHeight: 28 }} />
          {msgs.length > 0 && <button onClick={() => { setMsgs([]); LS.set(AI_KEY, []); }} title="Clear chat" className="rounded-lg p-2 text-zinc-400 hover:bg-zinc-100 hover:text-zinc-600 dark:hover:bg-zinc-800"><Icon name="reset" size={16} /></button>}
          <button onClick={() => send()} disabled={busy || !input.trim()} className="flex h-9 w-9 items-center justify-center rounded-xl text-white transition-all hover:brightness-110 disabled:opacity-40" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}><Icon name="arrow" size={17} className="-rotate-90" /></button>
        </div>
        <p className="mt-1.5 px-1 text-center text-[10.5px] text-zinc-400">AI can make mistakes — verify important strategy decisions. Reads your in-app data; nothing leaves your device except your questions.</p>
      </div>
    </div>
  );
}
window.AIAssistantPage = AIAssistantPage;
window.buildAIContext = buildAIContext;

/* ---- AI briefing card (used on Command Center) ---- */
const AI_BRIEF_KEY = 'vig2_ai_brief';
function AIBriefingCard({ go }) {
  const cached = LS.get(AI_BRIEF_KEY, null);
  const [brief, setBrief] = useStateAI(cached ? cached.text : '');
  const [ts, setTs] = useStateAI(cached ? cached.ts : 0);
  const [busy, setBusy] = useStateAI(false);
  const [err, setErr] = useStateAI('');

  // auto-run once per day (zero-tap)
  useEffectAI(() => {
    const c = LS.get(AI_BRIEF_KEY, null);
    const today = new Date().toISOString().slice(0, 10);
    const lastDay = c && c.ts ? new Date(c.ts).toISOString().slice(0, 10) : null;
    if (lastDay !== today && navigator.onLine !== false) { gen(); }
  }, []);

  const gen = async () => {
    setBusy(true); setErr('');
    try {
      const prompt = `${AI_SYS}\n\n${buildAIContext()}\n\nTASK: Give the player a punchy tactical briefing for today. Exactly 3 prioritized action items, each ONE short line starting with a strong verb, based on their snapshot (covenants to finish, troop/general gaps, alliance race). No preamble, no closing — just the 3 bullet lines.`;
      const reply = await window.claude.complete(prompt);
      const text = (reply || '').trim();
      setBrief(text); const now = Date.now(); setTs(now);
      LS.set(AI_BRIEF_KEY, { text, ts: now });
    } catch (e) { setErr('AI unavailable — needs internet and may be rate-limited.'); }
    finally { setBusy(false); }
  };

  const lines = brief.split('\n').map(l => l.replace(/^[-*•]\s*/, '').trim()).filter(Boolean).slice(0, 4);
  return (
    <section className="col-span-12 flex flex-col rounded-xl border border-zinc-800 bg-zinc-900">
      <header className="flex items-center justify-between border-b border-zinc-800 px-4 py-2.5">
        <div className="flex items-center gap-2">
          <span className="flex h-6 w-6 items-center justify-center rounded-md" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}><Icon name="sparkle" size={13} className="text-white" /></span>
          <h3 className="text-[11px] font-bold uppercase tracking-[0.14em] text-zinc-400">AI Briefing</h3>
          {ts > 0 && <span className="text-[10.5px] text-zinc-600">{syncTimeAgo ? syncTimeAgo(ts) : ''}</span>}
        </div>
        <div className="flex items-center gap-2">
          {brief && <button onClick={() => go('ai')} className="text-[11.5px] font-semibold text-zinc-400 hover:text-brand">Open chat →</button>}
          <button onClick={gen} disabled={busy} className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-[11.5px] font-semibold text-white transition-all hover:brightness-110 disabled:opacity-50" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}>
            <Icon name={busy ? 'reset' : 'sparkle'} size={12} className={busy ? 'animate-spin' : ''} />{busy ? 'Thinking…' : brief ? 'Refresh' : 'Generate'}
          </button>
        </div>
      </header>
      <div className="p-4">
        {err && <div className="text-[12.5px] text-rose-400">{err}</div>}
        {!brief && !err && <div className="text-[12.5px] text-zinc-500">Get a 3-point tactical briefing for today, generated from your live account &amp; alliance data.</div>}
        {brief && (
          <div className="grid grid-cols-1 gap-2 sm:grid-cols-3">
            {lines.map((l, i) => (
              <div key={i} className="flex gap-2.5 rounded-lg border border-zinc-800 bg-zinc-950/40 p-3">
                <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-brand/15 text-[11px] font-bold text-brand">{i + 1}</span>
                <span className="text-[12.5px] leading-snug text-zinc-200">{l.split(/(\*\*[^*]+\*\*)/g).map((p, j) => p.startsWith('**') && p.endsWith('**') ? <strong key={j} className="text-white">{p.slice(2, -2)}</strong> : p)}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
window.AIBriefingCard = AIBriefingCard;
