/**
 * app_bridge.js
 * - Provides a stable bridge between Flutter and the existing start-mining.html JS.
 * - Exposes window.NF_APP_INIT(payload) called from Flutter.
 * - Polls the existing DOM/variables to produce a simple stats object for Flutter UI.
 */

// State that Flutter reads (MinerScreen polls it via evaluateJavascript).
window.NF_APP_STATE = {
  confirmed: "—",
  pending: "—",
  effectiveHps: "—",
  blocksFound: "0",
};

function _safeText(sel){
  try{
    const el = document.querySelector(sel);
    const t = (el && el.textContent) ? el.textContent.trim() : "";
    return t || "";
  }catch(_){ return ""; }
}

function _setState(partial){
  try{ Object.assign(window.NF_APP_STATE, partial); }catch(_){}
}

function _human(n){
  const v = Number(n);
  if(!Number.isFinite(v) || v <= 0) return "0 H/s";
  const units=["H/s","KH/s","MH/s","GH/s","TH/s","PH/s"];
  let u=0, x=v;
  while(x>=1000 && u<units.length-1){ x/=1000; u++; }
  const dec = (x>=100)?0:(x>=10?1:2);
  return x.toFixed(dec)+" "+units[u];
}


function _cookieOpts(){
  const isHttps = location.protocol === "https:";
  const host = (location.hostname || "").toLowerCase();

  // If we are on *.nf-cash.com we can share cookies across subdomains.
  const isNFCash = host === "nf-cash.com" || host.endsWith(".nf-cash.com");

  const parts = [];
  parts.push("Path=/");
  if(isNFCash) parts.push("Domain=.nf-cash.com");
  // Lax is usually best for normal navigation while still being sent on top-level clicks.
  parts.push("SameSite=Lax");
  if(isHttps) parts.push("Secure");
  // 1 year
  parts.push("Max-Age=" + String(60*60*24*365));
  return "; " + parts.join("; ");
}

function _setCookie(name, value){
  try{
    if(value === undefined || value === null) return;
    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(String(value)) + _cookieOpts();
  }catch(_){}
}

function _getCookie(name){
  try{
    const n = encodeURIComponent(name) + "=";
    const parts = (document.cookie || "").split("; ");
    for(const p of parts){
      if(p.indexOf(n) === 0) return decodeURIComponent(p.substring(n.length));
    }
  }catch(_){}
  return "";
}

// Ensure localStorage and cookies stay in sync for public session fields.
// IMPORTANT: we DO NOT write private keys to cookies.
function _syncSessionStorage(){
  try{
    const cAddr = (_getCookie("nf_wallet_address") || _getCookie("nf_wallet") || "").trim();
    const lsAddr = (localStorage.getItem("nf_wallet_address") || localStorage.getItem("nf_wallet") || "").trim();
    const addr = lsAddr || cAddr;

    const cAvI = (_getCookie("nf_avatar_index") || "").trim();
    const lsAvI = (localStorage.getItem("nf_avatar_index") || "").trim();
    const avI = (lsAvI !== "" ? lsAvI : cAvI);

    const cAv = (_getCookie("nf_avatar") || "").trim();
    const lsAv = (localStorage.getItem("nf_avatar") || "").trim();
    const av = (lsAv !== "" ? lsAv : cAv);

    // Pull -> localStorage (when coming from another subdomain / fresh webview)
    if(addr && !lsAddr){
      localStorage.setItem("nf_wallet", addr);
      localStorage.setItem("nf_wallet_address", addr);
    }
    if(avI !== "" && lsAvI === ""){
      localStorage.setItem("nf_avatar_index", String(avI));
    }
    if(av && !lsAv){
      localStorage.setItem("nf_avatar", String(av));
    }

    // Push -> cookies (so nf-cash.com and mining.nf-cash.com stay connected)
    if(addr && !cAddr){
      _setCookie("nf_wallet", addr);
      _setCookie("nf_wallet_address", addr);
    }
    if(avI !== "" && !cAvI){
      _setCookie("nf_avatar_index", String(avI));
    }
    if(av && !cAv){
      _setCookie("nf_avatar", String(av));
    }
  }catch(_){}
}


// Called by Flutter after web content injected.
window.NF_APP_INIT = function(payload){
  try{
    // If this page was opened from another subdomain / webview, recover session.
    _syncSessionStorage();
    // Persist same keys used by your site:
    // - nf_wallet
    // - nf_wallet_address
    // - nf_wallet_private / nf_privkey
    if(payload && payload.address){
      const addr = String(payload.address).trim();
      localStorage.setItem("nf_wallet", addr);
      localStorage.setItem("nf_wallet_address", addr);

      // Share session across subdomains (nf-cash.com + mining.nf-cash.com)
      _setCookie("nf_wallet", addr);
      _setCookie("nf_wallet_address", addr);
    }
    if(payload && payload.privateKeyHex){
      localStorage.setItem("nf_wallet_private", payload.privateKeyHex);
      localStorage.setItem("nf_privkey", payload.privateKeyHex);
    }
    if(payload && payload.avatarIndex !== undefined && payload.avatarIndex !== null){
      const idx = String(payload.avatarIndex);
      const file = /^\d+$/.test(idx) ? ("nf_mine_" + idx + ".png") : idx;

      localStorage.setItem("nf_avatar_index", idx);
      localStorage.setItem("nf_avatar", file);

      // Share across subdomains
      _setCookie("nf_avatar_index", idx);
      _setCookie("nf_avatar", file);
    }

    // If your start-mining.js uses global helper to update UI, call it.
    try{
      if(window.NFWalletGlobal && typeof window.NFWalletGlobal.updateUI === "function"){
        window.NFWalletGlobal.updateUI();
      }
    }catch(_){}

    // Start a light polling loop for stats.
    if(!window.__nf_app_poll){
      window.__nf_app_poll = setInterval(function(){
        // confirmed balance box id in your HTML: #nfWalletBalance fileciteturn2file1
        const confirmed = _safeText("#nfWalletBalance") || _safeText("#nfBalance") || "—";
        // pending rewards box id: #nfPendingRewards fileciteturn2file1
        const pending = _safeText("#nfPendingRewards") || _safeText("#nfPending") || "—";

        // effective hps is displayed in #nfEffectivePower fileciteturn3file8
        let eff = _safeText("#nfEffectivePower");
        if(!eff){
          // fallback raw number if your JS sets __nf_local_hps_raw fileciteturn3file5
          const raw = (globalThis.__nf_local_hps_raw != null) ? Number(globalThis.__nf_local_hps_raw) : 0;
          eff = raw ? _human(raw) : "—";
        }

        const blocksFound = _safeText('#nfBlocksFound') || '0';
        _setState({ confirmed, pending, effectiveHps: eff, blocksFound });
      }, 600);
    }
  }catch(e){
    console.log("[NF_APP_INIT] error", e);
  }
};


// Expose manual sync (optional).
window.NF_APP_SYNC_SESSION = function(){
  try{ _syncSessionStorage(); }catch(_){}
};

// Auto-sync once on load to reduce 'disconnected' flashes.
try{ _syncSessionStorage(); }catch(_){}
