// ViG Command Center — Growth Roadmap (personalized progression planner)
const { useState: useStateGR, useMemo: useMemoGR, useEffect: useEffectGR } = React;

const GR_FOCUS = [['attack', 'PvP Attacker', '⚔️'], ['defense', 'Defender / Wall', '🛡️'], ['monster', 'Monster Hunter', '🐲'], ['balanced', 'Balanced', '⚖️']];
const GR_SPEND = [['ftp', 'F2P'], ['low', 'Low'], ['mid', 'Mid'], ['high', 'High']];

/* phase template builder — grounded checklist tied to the app's tools */
function grBuild(cur, tgt, focus, spend) {
  const phases = [];
  const span = Math.max(1, tgt - cur);
  const step = span <= 3 ? 1 : span <= 6 ? 2 : 3;
  let lvl = cur;
  let n = 1;
  while (lvl < tgt) {
    const to = Math.min(tgt, lvl + step);
    const actions = [];
    actions.push({ t: `Push Keep ${lvl} → ${to}`, tool: 'construction', why: 'Bank the exact RSS bill first' });
    actions.push({ t: 'Keep research moving', tool: 'academy', why: 'Stack research speed; never idle the Academy' });
    if (focus === 'attack') actions.push({ t: 'Train your highest troop tier', tool: 'troop', why: 'Attackers win on tier + buffs' });
    else if (focus === 'defense') actions.push({ t: 'Build wall traps & defending buffs', tool: 'rallysize', why: 'Survive incoming rallies' });
    else if (focus === 'monster') actions.push({ t: 'Gear for monster hunting', tool: 'gear', why: 'Basic + Attacking + Monster buffs' });
    else actions.push({ t: 'Balance troops & defense', tool: 'troop', why: 'Flexible across PvP and PvE' });
    actions.push({ t: 'Close covenants you can finish', tool: 'roster', why: 'Permanent buffs per general acquired' });
    phases.push({ n, range: `K${lvl}–K${to}`, focus, actions });
    lvl = to; n++;
    if (n > 6) break;
  }
  // spend-tuned headline
  const tone = { ftp: 'Patience & efficiency win — prioritise free RSS, events and covenant value.', low: 'Spend on value packs only; let covenants and research carry you.', mid: 'Invest in your main troop type and a specialist dragon per march.', high: 'Specialise hard — max gear, dragons and generals across every troop type.' }[spend];
  return { phases, tone };
}

function GrowthRoadmapPage({ go }) {
  const [cur, setCur] = useStateGR(() => LS.get('vig2_gr_cur', 40));
  const [tgt, setTgt] = useStateGR(() => LS.get('vig2_gr_tgt', 50));
  const [focus, setFocus] = useStateGR(() => LS.get('vig2_gr_focus', 'attack'));
  const [spend, setSpend] = useStateGR(() => LS.get('vig2_gr_spend', 'low'));
  const [aiPlan, setAiPlan] = useStateGR(() => LS.get('vig2_gr_ai', null));
  const [busy, setBusy] = useStateGR(false);
  const [err, setErr] = useStateGR('');
  useEffectGR(() => { LS.set('vig2_gr_cur', cur); }, [cur]);
  useEffectGR(() => { LS.set('vig2_gr_tgt', tgt); }, [tgt]);
  useEffectGR(() => { LS.set('vig2_gr_focus', focus); }, [focus]);
  useEffectGR(() => { LS.set('vig2_gr_spend', spend); }, [spend]);

  const plan = useMemoGR(() => grBuild(cur, Math.max(cur + 1, tgt), focus, spend), [cur, tgt, focus, spend]);
  const focusMeta = GR_FOCUS.find(f => f[0] === focus);

  const genAI = async () => {
    setBusy(true); setErr('');
    try {
      const ctx = (window.buildAIContext && window.buildAIContext()) || '';
      const prompt = `You are an Evony progression coach. The player is Keep ${cur}, targeting Keep ${tgt}, playstyle "${focusMeta[1]}", spend level "${spend}".\n\n${ctx}\n\nWrite a focused growth roadmap as 4 short numbered phases. Each phase: a bold title line then 2 brief bullet actions. No preamble. Tailor to their owned generals and covenant progress.`;
      const reply = await window.claude.complete(prompt);
      const text = (reply || '').trim();
      setAiPlan({ text, ts: Date.now() }); LS.set('vig2_gr_ai', { text, ts: Date.now() });
    } catch (e) { setErr('AI unavailable — needs internet and may be rate-limited.'); }
    finally { setBusy(false); }
  };

  const TOOL_LABEL = { construction: '🏯 Keep', academy: '🎓 Academy', troop: '🏹 Troop Training', rallysize: '🚩 Rally', gear: '🛡️ Gear', roster: '🎯 Roster' };

  return (
    <div className="space-y-4">
      {/* inputs */}
      <Card className="space-y-4 p-4">
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Current Keep · K{cur}</label>
            <input type="range" min="30" max="49" value={cur} onChange={e => { const v = +e.target.value; setCur(v); if (tgt <= v) setTgt(Math.min(50, v + 1)); }} className="w-full accent-[#FF6B00]" />
          </div>
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Target Keep · K{tgt}</label>
            <input type="range" min={cur + 1} max="50" value={tgt} onChange={e => setTgt(+e.target.value)} className="w-full accent-[#FF6B00]" />
          </div>
        </div>
        <div className="flex flex-wrap items-end gap-x-6 gap-y-3">
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Playstyle</label>
            <div className="flex flex-wrap gap-1.5">
              {GR_FOCUS.map(([id, label, emoji]) => (
                <button key={id} onClick={() => setFocus(id)} className={`flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[12px] font-semibold transition-colors ${focus === id ? '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'}`}><span>{emoji}</span>{label}</button>
              ))}
            </div>
          </div>
          <div>
            <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-zinc-400">Spend level</label>
            <div className="flex h-9 items-center"><Segmented options={GR_SPEND.map(s => ({ value: s[0], label: s[1] }))} value={spend} onChange={setSpend} /></div>
          </div>
          <button onClick={genAI} disabled={busy} className="ml-auto 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-50" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}>
            <Icon name={busy ? 'reset' : 'sparkle'} size={14} className={busy ? 'animate-spin' : ''} />{busy ? 'Planning…' : 'AI roadmap'}
          </button>
        </div>
        <div className="rounded-lg bg-brand/5 px-3.5 py-2.5 text-[12.5px] text-zinc-600 dark:text-zinc-300"><b className="text-brand">{focusMeta[2]} {focusMeta[1]} · {GR_SPEND.find(s => s[0] === spend)[1]} spend:</b> {plan.tone}</div>
      </Card>

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

      {/* AI plan */}
      {aiPlan && (
        <Card className="overflow-hidden border-brand/30">
          <div className="flex items-center gap-2 border-b border-zinc-100 px-4 py-2.5 dark:border-zinc-800"><Icon name="sparkle" size={15} className="text-brand" /><span className="text-[12.5px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">AI personalized roadmap</span><button onClick={() => { setAiPlan(null); LS.set('vig2_gr_ai', null); }} className="ml-auto text-[11.5px] text-zinc-400 hover:text-brand">Dismiss</button></div>
          <div className="space-y-1 p-4 text-[13px] leading-relaxed text-zinc-700 dark:text-zinc-200">
            {aiPlan.text.split('\n').filter(l => l.trim()).map((l, i) => {
              const parts = l.split(/(\*\*[^*]+\*\*)/g).map((p, j) => p.startsWith('**') ? <strong key={j} className="text-zinc-900 dark:text-white">{p.slice(2, -2)}</strong> : p);
              return <p key={i} className={/^\s*\d+[.)]/.test(l) ? 'mt-2 font-semibold' : 'pl-3'}>{parts}</p>;
            })}
          </div>
        </Card>
      )}

      {/* computed phases */}
      <div className="space-y-3">
        {plan.phases.map((ph, i) => (
          <Card key={i} className="overflow-hidden">
            <div className="flex items-center gap-3 border-b border-zinc-100 px-4 py-2.5 dark:border-zinc-800">
              <span className="flex h-7 w-7 items-center justify-center rounded-lg bg-brand text-[13px] font-bold text-white">{ph.n}</span>
              <span className="text-[13.5px] font-bold text-zinc-900 dark:text-white">Phase {ph.n}</span>
              <span className="rounded-full bg-zinc-100 px-2 py-0.5 text-[11px] font-semibold text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400">{ph.range}</span>
            </div>
            <div className="divide-y divide-zinc-50 dark:divide-zinc-800/60">
              {ph.actions.map((a, j) => (
                <button key={j} onClick={() => go(a.tool)} className="flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-zinc-50 dark:hover:bg-zinc-800/40">
                  <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 border-zinc-300 dark:border-zinc-600"></span>
                  <span className="min-w-0 flex-1">
                    <span className="block text-[13px] font-medium text-zinc-800 dark:text-zinc-100">{a.t}</span>
                    <span className="block text-[11.5px] text-zinc-400">{a.why}</span>
                  </span>
                  <span className="shrink-0 rounded-md bg-zinc-100 px-2 py-1 text-[11px] font-semibold text-zinc-500 dark:bg-zinc-800 dark:text-zinc-300">{TOOL_LABEL[a.tool]}</span>
                </button>
              ))}
            </div>
          </Card>
        ))}
      </div>

      <p className="px-1 text-[11.5px] text-zinc-400">This roadmap is a phased checklist tuned to your keep gap, playstyle and spend — tap any step to jump to the tool that handles it. Use <b>AI roadmap</b> for a plan personalized to your actual owned generals and covenant progress.</p>
    </div>
  );
}
window.GrowthRoadmapPage = GrowthRoadmapPage;
