// ViG Command Center — Guide & Learn center (real written guides + links into tools)
const { useState: useStateGD, useEffect: useEffectGD } = React;

const GUIDE_CATS = [
  {
    id: 'basics', icon: 'star', title: 'Getting Started',
    blurb: 'The fundamentals every ViG member should know.',
    articles: [
      { q: 'What should a new player prioritize?', a: [
        '**Keep level first.** Your Keep gates everything — troop tiers, building levels, march size. Push it steadily; never let it stall.',
        '**Pick one troop type to main.** Ground, Mounted, Ranged or Siege. Focus your generals, gear and research there before spreading out.',
        '**Mark what you own** in the General Database. The whole app — covenants, marches, health score — reacts to your real roster.',
        '**Join every rally and event.** Activity and alliance help outpace raw spending early on.',
      ] },
      { q: 'How do troop tiers work?', a: [
        'Troops go T1 → T17. Higher tiers cost far more but hit dramatically harder — one T17 is worth many T1s in power and combat stats.',
        'You unlock new tiers via Keep level + Academy research. Train the highest tier you can afford to maintain.',
        'Use the **Troop Training** calculator to see exact Food / Lumber / Stone / Ore / Gold and power per tier before you commit.',
      ], go: 'tools' },
      { q: 'What is "power" and does it matter?', a: [
        'Power is a rough score of your total progress — troops, buildings, research, generals, monarch gear.',
        'It signals strength but is **not** the whole story: a defensive wall account and an attacker can share the same power and perform completely differently.',
        'Track your power trend in **Account Analysis**; track the alliance race in the **War Room**.',
      ], go: 'analysis' },
    ],
  },
  {
    id: 'rally', icon: 'flame', title: 'Rally & March Playbook',
    blurb: 'Troop composition for rallies, layers and trap-busting.',
    articles: [
      { q: 'How should I fill a rally march?', a: [
        'Lead with your **highest tier** for the bulk of the march, then back-fill with the next tier or two so you maximize total stats without going all-glass.',
        'Match the **march type to your main**: Ground / Mounted / Ranged / Siege each want their specialist general + matching dragon and gear.',
        'The **March Size** tool builds exact compositions per rally type (Ground, Cavalry, Ranged, Siege, Trap Buster) for your march size and highest tier.',
      ], go: 'rallysize' },
      { q: 'What is a layer / layering?', a: [
        'A "layer" is a small reinforcement march (often a few thousand troops) sent into a rally or city to absorb a hit or pad the front.',
        'Your alliance coordinates layer sizes so the rally lead\u2019s real troops stay protected. Use the layer-size figure in the March tool.',
      ], go: 'rallysize' },
      { q: 'What is a Trap Buster march?', a: [
        'A Trap Buster is a specialized march built to trip and absorb an enemy\u2019s defensive traps before the main rally lands.',
        'It uses a specific thin composition — see the **Trap Buster** preset in March Size.',
      ], go: 'rallysize' },
    ],
  },
  {
    id: 'covenant', icon: 'link', title: 'Covenant Strategy',
    blurb: 'How covenants activate and which to chase first.',
    articles: [
      { q: 'How do covenants work?', a: [
        'A covenant activates only when you own **all** of its generals — the main plus its three partners.',
        'Once active it grants permanent buffs (attack, defense, HP, march speed, etc.) to your whole account.',
        'Partial covenants give nothing until the last general is owned — so finishing a covenant you\u2019re 1 general away from is huge value.',
      ] },
      { q: 'Which covenant should I finish next?', a: [
        'The **Covenant Center / Optimizer** ranks every incomplete covenant by buff value and how close you are (proximity).',
        'Prioritize high-value covenants where you\u2019re missing only 1 general — fastest buff per general acquired.',
      ], go: 'optimizer' },
    ],
  },
  {
    id: 'dragons', icon: 'star', title: 'Dragons & Beasts',
    blurb: 'Dragon roles, unlocks and who to run by spender level.',
    articles: [
      { q: 'Which dragon should I use?', a: [
        'Dragons buff a specific troop type or role. Match the dragon to the march it leads — the **Dragon Center** auto-recommends the strongest dragon per march from your roster.',
        'Free-to-play and light spenders should focus one or two versatile dragons; heavy spenders can specialize a dragon per troop type.',
      ], go: 'dragons' },
      { q: 'How do I compare two dragons?', a: [
        'Open the **Dragon Center**, hit **Compare**, and pick any two. You\u2019ll see troop-focus bars side by side, a "leads" verdict and full buff lists.',
      ], go: 'dragons' },
    ],
  },
  {
    id: 'speed', icon: 'bolt', title: 'Speed Stacking',
    blurb: 'Construction, research & training speed sources.',
    articles: [
      { q: 'How do I maximize research speed?', a: [
        'Research speed stacks from many sources — Monarch gear (Intellect Crown), Civilization treasures, Celtic dragon talent, duty officers, culture, sub-cities, VIP, alliance science and more.',
        'The **Academy** and **Military Academy** tabs include a full **Research Speed checklist** — tick what you have and see what\u2019s left.',
      ], go: 'academy' },
      { q: 'How do I plan a Keep upgrade?', a: [
        'The **Keep** tool breaks down K40\u2192K50 by level: RSS needed, your stockpile vs the gap, and a construction speed-buff checklist so you bank the right resources first.',
      ], go: 'construction' },
    ],
  },
  {
    id: 'gear', icon: 'shield', title: 'Gear & Specialty',
    blurb: 'Which buffs apply in which scenario.',
    articles: [
      { q: 'Which gear buffs count when?', a: [
        '**Attacking / Rallying:** Basic + Attacking buffs apply.',
        '**Reinforcing / Defending in a city:** Basic + In-City buffs apply.',
        '**Hitting monsters:** Basic + Attacking + Monster buffs apply.',
        'The **Gear Calculator** lets you build two loadouts and compares them under the scenario you pick.',
      ], go: 'gear' },
      { q: 'What is Flexible Specialty?', a: [
        'Specialties refine a general\u2019s strengths. "Flexible" specialties can be re-targeted to the buff you need for a given role.',
        'See the **Flexible Specialty** tab for the recommended specialty per general role.',
      ], go: 'flexspec' },
    ],
  },
  {
    id: 'app', icon: 'grid', title: 'Using This App',
    blurb: 'Get the most out of every module.',
    articles: [
      { q: 'How does the app know my account?', a: [
        'Mark generals as owned in the **General Database**. That ownership drives the Dashboard, Covenant Optimizer, Account Health score, march suggestions and the AI Assistant.',
        'Everything saves on your device — no account needed for the prototype.',
      ], go: 'generals' },
      { q: 'What can the AI Assistant do?', a: [
        'It reads your live snapshot — owned generals, covenant progress, alliance standings — and gives personalized advice. Ask it what to finish next, how to rally, or how ViG is doing vs rivals.',
      ], go: 'ai' },
      { q: 'How do I keep alliance data fresh?', a: [
        'The **War Room** syncs VIG / RSP / NEF standings and auto-refreshes every 24h. Use Live Sync to pull on demand, or Import/Export to paste a snapshot.',
      ], go: 'warroom' },
    ],
  },
];

function GuideArticle({ a, go }) {
  const [open, setOpen] = useStateGD(false);
  return (
    <div className="border-b border-zinc-100 last:border-0 dark:border-zinc-800">
      <button onClick={() => setOpen(o => !o)} className="flex w-full items-center gap-3 py-3 text-left">
        <span className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors ${open ? 'bg-brand text-white' : 'bg-zinc-100 text-zinc-400 dark:bg-zinc-800'}`}><Icon name={open ? 'x' : 'plus'} size={13} /></span>
        <span className="flex-1 text-[13.5px] font-semibold text-zinc-900 dark:text-white">{a.q}</span>
      </button>
      {open && (
        <div className="space-y-1.5 pb-4 pl-9 pr-2">
          {a.a.map((p, i) => {
            const parts = p.split(/(\*\*[^*]+\*\*)/g).map((x, j) => x.startsWith('**') && x.endsWith('**')
              ? <strong key={j} className="font-semibold text-zinc-900 dark:text-white">{x.slice(2, -2)}</strong> : x);
            return <p key={i} className="text-[13px] leading-relaxed text-zinc-600 dark:text-zinc-300">{parts}</p>;
          })}
          {a.go && <button onClick={() => go(a.go)} className="mt-1 inline-flex items-center gap-1 rounded-lg border border-brand/40 px-2.5 py-1 text-[12px] font-semibold text-brand transition-colors hover:bg-brand/10">Open the tool <Icon name="arrow" size={13} /></button>}
        </div>
      )}
    </div>
  );
}

function GuidePage({ go }) {
  const [cat, setCat] = useStateGD(() => LS.get('vig2_guide_cat', 'basics'));
  const [q, setQ] = useStateGD('');
  useEffectGD(() => { LS.set('vig2_guide_cat', cat); }, [cat]);

  const ql = q.trim().toLowerCase();
  const active = GUIDE_CATS.find(c => c.id === cat) || GUIDE_CATS[0];
  const searching = ql.length > 0;
  const results = searching
    ? GUIDE_CATS.flatMap(c => c.articles.filter(a => (a.q + ' ' + a.a.join(' ')).toLowerCase().includes(ql)).map(a => ({ a, cat: c })))
    : [];

  return (
    <div className="space-y-4">
      {/* hero */}
      <Card className="relative overflow-hidden p-5">
        <div className="relative flex items-center gap-4">
          <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)', boxShadow: '0 10px 28px -10px rgba(255,107,0,.7)' }}><Icon name="book" size={24} className="text-white" /></div>
          <div className="min-w-0 flex-1">
            <h2 className="text-[17px] font-bold text-zinc-900 dark:text-white">ViG Academy</h2>
            <p className="text-[12.5px] text-zinc-500 dark:text-zinc-400">Straight-talking Evony guides — then jump into the tool that does the math.</p>
          </div>
          <button onClick={() => go('ai')} className="hidden shrink-0 items-center gap-1.5 rounded-lg border border-zinc-200 px-3 py-2 text-[12.5px] font-semibold text-zinc-600 transition-colors hover:border-brand hover:text-brand dark:border-zinc-700 dark:text-zinc-300 sm:inline-flex"><Icon name="sparkle" size={14} />Ask the AI</button>
        </div>
        <div className="relative mt-4">
          <Icon name="search" size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400" />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search all guides…" className="h-10 w-full rounded-lg border border-zinc-200 bg-white pl-9 pr-3 text-[13px] outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" />
        </div>
      </Card>

      {searching ? (
        <Card className="p-4">
          <div className="mb-1 text-[11px] font-bold uppercase tracking-wide text-zinc-400">{results.length} result{results.length !== 1 ? 's' : ''}</div>
          {results.length ? results.map(({ a, cat }, i) => (
            <div key={i}>
              <div className="mt-2 text-[10.5px] font-semibold uppercase tracking-wide text-brand">{cat.title}</div>
              <GuideArticle a={a} go={go} />
            </div>
          )) : <div className="py-8 text-center text-[13px] text-zinc-400">No guides match — try the AI Assistant for anything specific.</div>}
        </Card>
      ) : (
        <div className="grid grid-cols-1 gap-4 lg:grid-cols-4">
          {/* topic rail */}
          <div className="lg:col-span-1">
            <div className="flex gap-2 overflow-x-auto pb-1 lg:flex-col lg:overflow-visible">
              {GUIDE_CATS.map(c => (
                <button key={c.id} onClick={() => setCat(c.id)} className={`flex shrink-0 items-center gap-2.5 rounded-xl border px-3 py-2.5 text-left transition-all lg:w-full ${cat === c.id ? 'border-brand bg-brand/5' : 'border-zinc-200 hover:border-zinc-300 dark:border-zinc-800 dark:hover:border-zinc-700'}`}>
                  <span className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${cat === c.id ? 'bg-brand text-white' : 'bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400'}`}><Icon name={c.icon} size={16} /></span>
                  <div className="min-w-0">
                    <div className={`text-[13px] font-semibold ${cat === c.id ? 'text-brand' : 'text-zinc-800 dark:text-zinc-200'}`}>{c.title}</div>
                    <div className="hidden text-[11px] text-zinc-400 lg:block">{c.articles.length} guides</div>
                  </div>
                </button>
              ))}
            </div>
          </div>
          {/* article list */}
          <div className="lg:col-span-3">
            <Card className="p-4">
              <div className="mb-1 flex items-center gap-2">
                <Icon name={active.icon} size={16} className="text-brand" />
                <h3 className="text-[14px] font-bold text-zinc-900 dark:text-white">{active.title}</h3>
              </div>
              <p className="mb-2 text-[12.5px] text-zinc-500 dark:text-zinc-400">{active.blurb}</p>
              {active.articles.map((a, i) => <GuideArticle key={i} a={a} go={go} />)}
            </Card>
          </div>
        </div>
      )}
    </div>
  );
}
window.GuidePage = GuidePage;
// flat searchable index for the ⌘K command palette
window.GUIDE_INDEX = GUIDE_CATS.flatMap(c => c.articles.map(a => ({ q: a.q, cat: c.title })));
