// playbook-store.jsx — single source of truth for designers + accounts
// Reads initial data from PDATA, persists overrides to localStorage.

const STORAGE_KEY = 'playbook-store-v2-anon';

// Build initial flat structures from PDATA seed
function buildSeedDesigners() {
  return window.PDATA.designers.map((d, i) => ({
    id: 'd' + (i + 1),
    name: d.name,
    role: d.role || 'Designer',
    email: d.email || '',
    initials: d.name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase(),
  }));
}

function buildSeedAccounts() {
  const out = [];
  let i = 1;
  for (const type of ['A', 'B', 'C']) {
    for (const item of window.PDATA.accounts[type].items) {
      out.push({
        id: 'a' + (i++),
        name: item.name,
        type: type,
        designerName: item.designer || null,
      });
    }
  }
  return out;
}

function loadStore() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      if (parsed && parsed.designers && parsed.accounts) return parsed;
    }
  } catch (e) {}
  return { designers: buildSeedDesigners(), accounts: buildSeedAccounts() };
}

function saveStore(state) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); } catch (e) {}
}

// Pub/sub for cross-section updates
const listeners = new Set();
let state = loadStore();

const Store = {
  get: () => state,
  getDesigners: () => state.designers,
  getAccounts: () => state.accounts,

  subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
  _emit() { listeners.forEach(fn => fn(state)); saveStore(state); },

  reset() {
    state = { designers: buildSeedDesigners(), accounts: buildSeedAccounts() };
    Store._emit();
  },

  // ── Designers ──
  addDesigner(d) {
    const id = 'd' + Date.now();
    const initials = (d.name || '').split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase();
    state.designers = [...state.designers, { id, ...d, initials }];
    Store._emit();
  },
  updateDesigner(id, patch) {
    state.designers = state.designers.map(d => {
      if (d.id !== id) return d;
      const next = { ...d, ...patch };
      if (patch.name) next.initials = patch.name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase();
      return next;
    });
    // If name changed, propagate to account.designerName
    if (patch.name) {
      const old = state.designers.find(d => d.id === id);
      // (already updated above; we need the previous name — handle in caller)
    }
    Store._emit();
  },
  removeDesigner(id) {
    const d = state.designers.find(x => x.id === id);
    if (!d) return;
    state.designers = state.designers.filter(x => x.id !== id);
    // Clear designerName on accounts that pointed to this designer
    state.accounts = state.accounts.map(a => a.designerName === d.name ? { ...a, designerName: null } : a);
    Store._emit();
  },
  // Reassign accounts when designer renamed (called from Gestão UI)
  renameDesigner(id, oldName, newName) {
    state.designers = state.designers.map(d => d.id === id ? { ...d, name: newName, initials: newName.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase() } : d);
    state.accounts = state.accounts.map(a => a.designerName === oldName ? { ...a, designerName: newName } : a);
    Store._emit();
  },

  // ── Accounts ──
  addAccount(a) {
    const id = 'a' + Date.now();
    state.accounts = [...state.accounts, { id, ...a }];
    Store._emit();
  },
  updateAccount(id, patch) {
    state.accounts = state.accounts.map(a => a.id === id ? { ...a, ...patch } : a);
    Store._emit();
  },
  removeAccount(id) {
    state.accounts = state.accounts.filter(a => a.id !== id);
    Store._emit();
  },

  // Helpers
  getAccountsByDesigner(name) {
    return state.accounts.filter(a => a.designerName === name);
  },
  getAccountsByType(type) {
    return state.accounts.filter(a => a.type === type);
  },
};

// React hook
function useStore() {
  const [, force] = React.useState(0);
  React.useEffect(() => Store.subscribe(() => force(n => n + 1)), []);
  return Store;
}

Object.assign(window, { Store, useStore });
