// ViG Command Center — Firebase cloud sync (shared roster + alliance standings)
// Loads Firebase compat SDK from CDN; no build step. Keys are public by design.
const { useState: useStateCL, useEffect: useEffectCL } = React;

const FIREBASE_CONFIG = {
  apiKey: "AIzaSyBZortZC3DHWNrz9syPNOOsxznm7b5GhnU",
  authDomain: "vig-intelligence.firebaseapp.com",
  projectId: "vig-intelligence",
  storageBucket: "vig-intelligence.firebasestorage.app",
  messagingSenderId: "833448261850",
  appId: "1:833448261850:web:2262d01cf684fb0c888de3",
};

const Cloud = {
  ready: false, db: null, _loading: null, _unsub: null,
  // lazy-load the SDK once
  load() {
    if (this.ready) return Promise.resolve(true);
    if (this._loading) return this._loading;
    this._loading = new Promise((resolve, reject) => {
      const add = (src) => new Promise((res, rej) => {
        const s = document.createElement('script'); s.src = src; s.onload = res; s.onerror = rej; document.head.appendChild(s);
      });
      add('https://www.gstatic.com/firebasejs/10.12.2/firebase-app-compat.js')
        .then(() => add('https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore-compat.js'))
        .then(() => {
          try {
            if (!window.firebase.apps.length) window.firebase.initializeApp(FIREBASE_CONFIG);
            this.db = window.firebase.firestore();
            this.ready = true; resolve(true);
          } catch (e) { reject(e); }
        })
        .catch(reject);
    });
    return this._loading;
  },
  // push this member's roster + summary into the shared alliance doc
  async pushMember(code, handle, payload) {
    await this.load();
    await this.db.collection('alliances').doc(code).collection('members').doc(handle)
      .set({ ...payload, updatedAt: Date.now() }, { merge: true });
  },
  // push shared alliance standings (any member can update the live feed)
  async pushStandings(code, standings) {
    await this.load();
    await this.db.collection('alliances').doc(code)
      .set({ standings, standingsAt: Date.now() }, { merge: true });
  },
  // live-listen to the whole alliance doc + members
  async subscribe(code, cb) {
    await this.load();
    if (this._unsub) this._unsub();
    const ref = this.db.collection('alliances').doc(code);
    const unsubDoc = ref.onSnapshot(d => cb({ type: 'doc', data: d.data() || {} }));
    const unsubMem = ref.collection('members').onSnapshot(snap => {
      const members = []; snap.forEach(m => members.push({ handle: m.id, ...m.data() }));
      cb({ type: 'members', members });
    });
    this._unsub = () => { unsubDoc(); unsubMem(); };
    return this._unsub;
  },
  disconnect() { if (this._unsub) { this._unsub(); this._unsub = null; } },
};
window.Cloud = Cloud;

function CloudSyncPanel() {
  const cfg0 = LS.get('vig2_cloud', { code: '', auto: false });
  const [code, setCode] = useStateCL(cfg0.code || '');
  const [status, setStatus] = useStateCL('idle'); // idle|connecting|live|error
  const [members, setMembers] = useStateCL([]);
  const [msg, setMsg] = useStateCL('');
  const session = LS.get('vig2_session', { handle: 'commander', name: 'Commander' });

  useEffectCL(() => () => Cloud.disconnect(), []);

  const connect = async () => {
    const c = code.trim().toLowerCase().replace(/[^a-z0-9-]/g, '');
    if (!c) { setMsg('Enter an alliance code (e.g. vig-428).'); return; }
    setStatus('connecting'); setMsg('');
    LS.set('vig2_cloud', { code: c, auto: true });
    try {
      await Cloud.subscribe(c, (ev) => {
        if (ev.type === 'members') setMembers(ev.members.sort((a, b) => (b.power || 0) - (a.power || 0)));
        setStatus('live');
      });
      // push my current roster immediately
      await pushMine(c);
      setStatus('live');
      setMsg('Connected to "' + c + '". Your roster is shared with everyone using this code.');
    } catch (e) { setStatus('error'); setMsg('Could not connect: ' + (e.message || 'check your network / Firestore rules.')); }
  };

  const pushMine = async (c) => {
    const own = LS.get('vig2_ownership', {});
    const owned = Object.keys(own).filter(k => own[k]);
    const V = window.VIG;
    let power = 0; try { power = (V.generals || []).filter(g => own[g.name + '|' + g.type]).reduce((s, g) => s + (g.totAtk || 0), 0); } catch (e) {}
    await Cloud.pushMember(c || code.trim().toLowerCase(), session.handle || 'me', { name: session.name || session.handle, owned: owned.length, power, role: session.role || 'Member' });
  };

  const disconnect = () => { Cloud.disconnect(); setStatus('idle'); setMembers([]); LS.set('vig2_cloud', { code, auto: false }); setMsg('Disconnected. Your data stays on this device.'); };

  const dot = { idle: '#6A6A6E', connecting: '#E8C271', live: '#34d399', error: '#fb7185' }[status];

  return (
    <Card className="overflow-hidden">
      <div className="flex items-center gap-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
        <Icon name="database" size={16} className="text-brand" />
        <span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Cloud Sync</span>
        <span className="ml-auto flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide" style={{ color: dot }}>
          <span className="h-2 w-2 rounded-full" style={{ background: dot, boxShadow: status === 'live' ? '0 0 7px ' + dot : 'none' }}></span>
          {status === 'live' ? 'Live' : status === 'connecting' ? 'Connecting…' : status === 'error' ? 'Error' : 'Offline'}
        </span>
      </div>
      <div className="space-y-3 p-4">
        <p className="text-[12.5px] text-zinc-500 dark:text-zinc-400">Enter a shared <b>alliance code</b> (everyone uses the same one, e.g. <span className="font-mono text-brand">vig-428</span>). Your roster syncs live to the cloud so every member sees the same data — real-time, across devices.</p>
        <div className="flex flex-wrap items-center gap-2">
          <input value={code} onChange={e => setCode(e.target.value)} placeholder="alliance code" className="h-10 flex-1 rounded-lg border border-zinc-200 bg-white px-3 font-mono text-[13px] outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" style={{ minWidth: 140 }} />
          {status === 'live'
            ? <><button onClick={() => pushMine()} className="inline-flex items-center gap-1.5 rounded-lg px-3.5 py-2 text-[12.5px] font-semibold text-white hover:brightness-110" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}><Icon name="reset" size={13} />Push my data</button>
               <button onClick={disconnect} className="rounded-lg border border-zinc-200 px-3 py-2 text-[12.5px] font-semibold text-zinc-500 hover:bg-zinc-50 dark:border-zinc-700 dark:hover:bg-zinc-800">Disconnect</button></>
            : <button onClick={connect} disabled={status === 'connecting'} 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-50" style={{ background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)' }}><Icon name="link" size={13} />{status === 'connecting' ? 'Connecting…' : 'Connect'}</button>}
        </div>
        {msg && <div className={`rounded-lg px-3 py-2 text-[12px] ${status === 'error' ? 'bg-rose-50 text-rose-600 dark:bg-rose-950/40 dark:text-rose-300' : 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300'}`}>{msg}</div>}
        {members.length > 0 && (
          <div className="rounded-xl border border-zinc-100 dark:border-zinc-800">
            <div className="border-b border-zinc-100 px-3 py-2 text-[10.5px] font-bold uppercase tracking-wide text-zinc-400 dark:border-zinc-800">{members.length} members synced · live</div>
            <div className="divide-y divide-zinc-50 dark:divide-zinc-800/60">
              {members.slice(0, 12).map((m, i) => (
                <div key={m.handle} className="flex items-center gap-3 px-3 py-2 text-[12.5px]">
                  <span className="w-5 text-center font-bold tabular-nums text-zinc-400">{i + 1}</span>
                  <span className="flex-1 truncate font-medium text-zinc-800 dark:text-zinc-100">{m.name || m.handle}</span>
                  <span className="text-[11px] text-zinc-400">{m.owned || 0} owned</span>
                  <span className="w-14 text-right font-bold tabular-nums text-brand">{m.power || 0}</span>
                </div>
              ))}
            </div>
          </div>
        )}
        <p className="text-[11px] text-zinc-400">Powered by Firebase Firestore. While in test mode, anyone with the code can read &amp; write — set Firestore security rules before going public. Your local data is never deleted by syncing.</p>
      </div>
    </Card>
  );
}
window.CloudSyncPanel = CloudSyncPanel;
