// 0root.ai lattice → IPFS logger
// Add this to your production lattice HTML before </script>

const IPFS_LOGGER = {
  endpoint: 'https://api.web3.storage/upload', // or your own
  token: localStorage.getItem('web3_token') || '',
  
  async logTrit(tritCount, N, phi, ternary) {
    const payload = {
      timestamp: new Date().toISOString(),
      trit: tritCount.toString(),
      N: N.toFixed(6),
      phi: phi.toFixed(6),
      ternary: ternary,
      hash: await this.sha256(`${tritCount}-${N}-${phi}`),
      origin: '0root.ai',
      claimant: 'David Lee Wise / TriPod LLC'
    };
    
    // local immutable log
    const log = JSON.parse(localStorage.getItem('lattice_ipfs_log') || '[]');
    log.push(payload);
    localStorage.setItem('lattice_ipfs_log', JSON.stringify(log.slice(-1000)));
    
    // optional IPFS pin
    if (this.token) {
      try {
        await fetch(this.endpoint, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(payload)
        });
      } catch(e) { /* fail silently */ }
    }
    return payload.hash;
  },
  
  async sha256(str) {
    const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(str));
    return [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2,'0')).join('');
  }
};

// Hook into your existing counter:
// In your trit increment function, add:
// IPFS_LOGGER.logTrit(tritCount, N, phi, currentTernary);