// Shared mock data + active-account state for the post-login account area.
// All four account pages (Overview, Applications, Find, Settings) read from
// this one source so the prototype stays internally consistent across navigation.

// ─── Account switching (persisted in localStorage) ──────────

const ACCOUNT_KEY = 'govpilot.activeAccount';
const ACCOUNT_EVENT = 'govpilot:account-changed';
function getActiveAccount() {
  try { return localStorage.getItem(ACCOUNT_KEY) || 'personal'; } catch { return 'personal'; }
}
function setActiveAccount(v) {
  try { localStorage.setItem(ACCOUNT_KEY, v); } catch {}
  // Same-tab pubsub — `storage` events only fire cross-tab, so every hook
  // instance needs this custom event to stay in sync.
  window.dispatchEvent(new CustomEvent(ACCOUNT_EVENT, { detail: v }));
}
function useActiveAccount() {
  const [a, setA] = React.useState(getActiveAccount());
  React.useEffect(() => {
    const onChange = () => setA(getActiveAccount());
    window.addEventListener(ACCOUNT_EVENT, onChange);
    window.addEventListener('storage', (e) => { if (e.key === ACCOUNT_KEY) onChange(); });
    return () => window.removeEventListener(ACCOUNT_EVENT, onChange);
  }, []);
  const set = React.useCallback((v) => { setActiveAccount(v); }, []);
  return [a, set];
}

// ─── Signed-in flag (persisted in localStorage) ─────────────
// Public-portal pages read this to show the avatar pill instead of the
// "Sign in" button. Set to true when AccountTopBar mounts (you arrive on
// the account area only via signing in); cleared when the user clicks
// Sign out. Also mirrored to <html data-signed-in="true"> by an inline
// pre-paint script in every static-header HTML so the right pill renders
// on first paint.
const SIGNEDIN_KEY = 'govpilot.signedIn';
const SIGNEDIN_EVENT = 'govpilot:signed-in-changed';
function getSignedIn() {
  try { return localStorage.getItem(SIGNEDIN_KEY) === 'true'; } catch { return false; }
}
function setSignedIn(v) {
  try {
    if (v) localStorage.setItem(SIGNEDIN_KEY, 'true');
    else localStorage.removeItem(SIGNEDIN_KEY);
  } catch {}
  // Keep <html> attribute in sync so the static-HTML CSS rules update
  // immediately within the same page (e.g. after Sign out before navigation).
  try {
    if (v) document.documentElement.setAttribute('data-signed-in', 'true');
    else document.documentElement.removeAttribute('data-signed-in');
  } catch {}
  window.dispatchEvent(new CustomEvent(SIGNEDIN_EVENT, { detail: !!v }));
}
function useSignedIn() {
  const [s, setS] = React.useState(getSignedIn());
  React.useEffect(() => {
    const onChange = () => setS(getSignedIn());
    window.addEventListener(SIGNEDIN_EVENT, onChange);
    window.addEventListener('storage', (e) => { if (e.key === SIGNEDIN_KEY) onChange(); });
    return () => {
      window.removeEventListener(SIGNEDIN_EVENT, onChange);
    };
  }, []);
  return [s, setSignedIn];
}

// ─── Profiles ────────────────────────────────────────────────

const ACCOUNTS = {
  personal: {
    kind: 'personal',
    name: 'Jamie Morrison',
    short: 'Jamie M.',
    initials: 'JM',
    email: 'jamie.morrison@email.com',
    phone: '(609) 555-0142',
    primaryMuni: 'Montgomery',
    properties: [
      { id: 'p1', label: '14 Oak Lane',         muni: 'Montgomery',   relation: 'Owner',  primary: true,  block: '42 / 18' },
      { id: 'p2', label: 'Sunset Cabin',        muni: 'Montclair',    relation: 'Owner',  primary: false, block: '08 / 21' },
      { id: 'p3', label: '88 Bell St',          muni: 'Hillsborough', relation: 'Tenant', primary: false, block: '17 / 04' },
    ],
    pets: [
      { id: 'pet1', name: 'Beans',   species: 'Dog', breed: 'Mixed',  status: 'Renewal due' },
      { id: 'pet2', name: 'Pickle',  species: 'Cat', breed: 'Tabby',  status: 'No license needed' },
    ],
  },
  business: {
    kind: 'business',
    name: 'Acme Plumbing LLC',
    short: 'Acme Plumbing',
    initials: 'AP',
    email: 'ops@acmeplumbing.com',
    phone: '(908) 555-0190',
    ein: '47-1234567',
    primaryMuni: 'Hillsborough',
    addresses: ['212 Industrial Way, Hillsborough NJ'],
    team: [
      { id: 't1', name: 'Jamie Morrison', initials: 'JM', role: 'Owner' },
      { id: 't2', name: 'Riley Diaz',     initials: 'RD', role: 'Authorized' },
    ],
    properties: [
      { id: 'b1', label: '212 Industrial Way', muni: 'Hillsborough', relation: 'Owner', primary: true, block: '03 / 12' },
    ],
    // job sites — properties we're working on but don't own
    sites: [
      { id: 'js1', label: '88 Bell St',     muni: 'Montgomery',   active: 2 },
      { id: 'js2', label: '14 Park Ave',    muni: 'Montclair',    active: 2 },
      { id: 'js3', label: '410 Main St',    muni: 'Princeton',    active: 1 },
      { id: 'js4', label: '212 Industrial', muni: 'Hillsborough', active: 1 },
      { id: 'js5', label: '30 Birch Rd',    muni: 'Hillsborough', active: 1 },
      { id: 'js6', label: '22 Elm St',      muni: 'Montgomery',   active: 1 },
      { id: 'js7', label: '17 Park Ln',     muni: 'Montclair',    active: 1 },
      { id: 'js8', label: '910 Bell St',    muni: 'Princeton',    active: 1 },
    ],
  },
};

// ─── Applications (the canonical dataset for both accounts) ─

const APPS = {
  personal: [
    // action
    { code: 'DL-2026-0184', type: 'Dog License renewal',        subject: 'Beans',                muni: 'Montgomery',   property: '14 Oak Lane',   status: 'Payment due',         when: 'Due in 3 days',   bucket: 'action', cta: 'Pay $25', detail: 'Once paid your license issues automatically.' },
    { code: 'BP-2026-1102', type: 'Roofing Permit',             subject: '14 Oak Lane',          muni: 'Hillsborough', property: '88 Bell St',    status: 'Awaiting signature',  when: 'Linked 2d ago',   bucket: 'action', cta: 'Documentation Requested',     tag: 'as homeowner', detail: 'ABC Roofing linked you as the homeowner.' },
    // in progress
    { code: 'ZP-2026-0431', type: 'Zoning Permit',              subject: 'Driveway',             muni: 'Montgomery',   property: '14 Oak Lane',   status: 'Approved',            when: 'Updated yesterday', bucket: 'active' },
    { code: 'SE-2026-0009', type: 'Block Party Permit',         subject: 'Hillside Rd',          muni: 'Montclair',    property: 'Sunset Cabin',  status: 'Under review',        when: 'Filed Mon',         bucket: 'active' },
    { code: 'BP-2026-0876', type: 'Fence Permit',               subject: '14 Oak Lane',          muni: 'Montgomery',   property: '14 Oak Lane',   status: 'Approved · pickup',   when: 'Approved 3d ago',   bucket: 'active' },
    { code: 'SE-2026-0021', type: 'Block Party Permit',         subject: '4th of July',          muni: 'Montgomery',   property: '14 Oak Lane',   status: 'Under review',        when: 'Filed May 18',      bucket: 'active' },
    { code: 'GS-2026-0144', type: 'Garage Sale Permit',         subject: '14 Oak Lane',          muni: 'Montgomery',   property: '14 Oak Lane',   status: 'Under review',        when: 'Filed May 20',      bucket: 'active' },
    { code: 'OP-2026-0033', type: 'OPRA Records Request',       subject: 'Tax assessment',       muni: 'Montgomery',   property: '14 Oak Lane',   status: 'In review',           when: '4d ago',            bucket: 'active' },
    // drafts
    { code: '—',            type: 'Solar Panel Installation',   subject: '14 Oak Lane',          muni: 'Montgomery',   property: '14 Oak Lane',   status: '30% complete',        when: 'Saved 4d ago',      bucket: 'draft' },
    { code: '—',            type: 'OPRA Records Request',       subject: 'Sunset Cabin',         muni: 'Montclair',    property: 'Sunset Cabin',  status: '80% complete',        when: 'Saved 11d ago',     bucket: 'draft' },
    { code: '—',            type: 'Pool Permit',                subject: '88 Bell St',           muni: 'Hillsborough', property: '88 Bell St',    status: '10% complete',        when: 'Saved 18d ago',     bucket: 'draft' },
    // closed
    { code: 'DL-2025-0184', type: 'Dog License',                subject: 'Beans (prior year)',   muni: 'Montgomery',   property: '14 Oak Lane',   status: 'Expired',             when: 'May 2026',          bucket: 'closed' },
    { code: 'SE-2025-1148', type: 'Block Party Permit',         subject: 'NYE 2025',             muni: 'Montgomery',   property: '14 Oak Lane',   status: 'Completed',           when: 'Dec 2025',          bucket: 'closed' },
  ],
  business: [
    // action
    { code: 'BP-2026-1203', type: 'Plumbing Permit',            subject: '88 Bell St',           muni: 'Montgomery',   property: '88 Bell St',     status: 'Inspection failed · schedule re-inspection', when: '1d ago', bucket: 'action', cta: 'Schedule Inspection' },
    { code: 'BP-2026-1240', type: 'Water Heater Permit',        subject: '14 Park Ave',          muni: 'Montclair',    property: '14 Park Ave',    status: 'Fee due · $185',               when: '2d ago', bucket: 'action', cta: 'Pay' },
    { code: 'BP-2026-1268', type: 'Backflow Test',              subject: '410 Main St',          muni: 'Princeton',    property: '410 Main St',    status: 'Awaiting your signature',      when: '3d ago', bucket: 'action', cta: 'Sign', tag: 'as contractor' },
    // active
    { code: 'BP-2026-1004', type: 'Water Heater Permit',        subject: '212 Industrial',       muni: 'Hillsborough', property: '212 Industrial', status: 'Inspection scheduled',         when: 'May 28 · 10am',  bucket: 'active' },
    { code: 'BP-2026-1110', type: 'Plumbing Permit',            subject: '30 Birch Rd',          muni: 'Hillsborough', property: '30 Birch Rd',    status: 'Under review',                 when: 'Filed May 14',   bucket: 'active' },
    { code: 'BP-2026-1135', type: 'Sewer Connection Permit',    subject: '17 Park Ln',           muni: 'Montclair',    property: '17 Park Ln',     status: 'Under review',                 when: 'Filed May 16',   bucket: 'active' },
    { code: 'BP-2026-1155', type: 'Backflow Test',              subject: '910 Bell St',          muni: 'Princeton',    property: '910 Bell St',    status: 'Approved',                     when: 'May 18',         bucket: 'active' },
    { code: 'BP-2026-1180', type: 'Gas Line Permit',            subject: '22 Elm St',            muni: 'Montgomery',   property: '22 Elm St',      status: 'Under review',                 when: 'Filed May 19',   bucket: 'active' },
    { code: 'BP-2026-1198', type: 'Water Heater Permit',        subject: '88 Bell St',           muni: 'Montgomery',   property: '88 Bell St',     status: 'Inspection scheduled',         when: 'May 27',         bucket: 'active' },
    // drafts
    { code: '—',            type: 'Pool Permit',                subject: '30 Birch Rd',          muni: 'Hillsborough', property: '30 Birch Rd',    status: '60% complete',                 when: 'Saved 2d ago',   bucket: 'draft' },
    { code: '—',            type: 'Reroof Permit',              subject: '22 Elm St',            muni: 'Montgomery',   property: '22 Elm St',      status: '15% complete',                 when: 'Saved 5d ago',   bucket: 'draft' },
    // closed
    { code: 'BP-2026-1230', type: 'Backflow Test',              subject: '12 Maple Ave',         muni: 'Princeton',    property: '12 Maple Ave',   status: 'Closed',                       when: 'May 22',         bucket: 'closed' },
  ],
};

// ─── Activity feed ──────────────────────────────────────────

const ACTIVITY = {
  personal: [
    { when: '9:14 AM today',    text: 'Beans dog license — payment required by Friday',     ref: 'DL-2026-0184', muni: 'Montgomery',   action: true },
    { when: '8:02 AM today',    text: 'ABC Roofing linked you to roofing permit',           ref: 'BP-2026-1102', muni: 'Hillsborough', action: true },
    { when: 'Yesterday 4:31 PM', text: 'Driveway zoning permit approved',                    ref: 'ZP-2026-0431', muni: 'Montgomery' },
    { when: 'Yesterday 2:10 PM', text: 'Block party permit submitted',                       ref: 'SE-2026-0009', muni: 'Montclair' },
    { when: 'May 23',            text: 'Fence permit approved — pickup available',           ref: 'BP-2026-0876', muni: 'Montgomery' },
    { when: 'May 22',            text: 'OPRA tax-assessment request acknowledged',           ref: 'OP-2026-0033', muni: 'Montgomery' },
  ],
  business: [
    { when: '11:30 AM today',   text: '88 Bell St inspection failed — inspector note',      ref: 'BP-2026-1203', muni: 'Montgomery',   action: true },
    { when: '9:02 AM today',    text: '14 Park water heater fee invoice issued',            ref: 'BP-2026-1240', muni: 'Montclair',    action: true },
    { when: 'Yesterday',         text: '410 Main backflow — homeowner signature requested',  ref: 'BP-2026-1268', muni: 'Princeton',    action: true },
    { when: 'May 22',            text: '12 Maple backflow closed',                            ref: 'BP-2026-1230', muni: 'Princeton' },
    { when: 'May 21',            text: 'Riley started new permit · 30 Birch Pool',           ref: '—',            muni: 'Hillsborough' },
    { when: 'May 18',            text: '910 Bell St backflow approved',                       ref: 'BP-2026-1155', muni: 'Princeton' },
  ],
};

// ─── Derived helpers ────────────────────────────────────────

function countByBucket(account) {
  const list = APPS[account];
  return {
    action: list.filter(a => a.bucket === 'action').length,
    active: list.filter(a => a.bucket === 'active').length,
    draft:  list.filter(a => a.bucket === 'draft').length,
    closed: list.filter(a => a.bucket === 'closed').length,
    open:   list.filter(a => a.bucket !== 'closed').length,
  };
}

function sliceByMuni(account) {
  const list = APPS[account].filter(a => a.bucket !== 'closed');
  const byMuni = {};
  for (const a of list) {
    byMuni[a.muni] = byMuni[a.muni] || { muni: a.muni, count: 0, action: 0, primary: a.muni === ACCOUNTS[account].primaryMuni };
    byMuni[a.muni].count++;
    if (a.bucket === 'action') byMuni[a.muni].action++;
  }
  return Object.values(byMuni).sort((a, b) => (b.action - a.action) || (b.count - a.count));
}

function sliceByProperty(account) {
  const list = APPS[account].filter(a => a.bucket !== 'closed');
  const byProp = {};
  for (const a of list) {
    byProp[a.property] = byProp[a.property] || { property: a.property, muni: a.muni, count: 0, action: 0 };
    byProp[a.property].count++;
    if (a.bucket === 'action') byProp[a.property].action++;
  }
  return Object.values(byProp).sort((a, b) => (b.action - a.action) || (b.count - a.count));
}

// Notifications count for the bell badge (sum of action items the user owns).
function notifCount(account) {
  return ACTIVITY[account].filter(a => a.action).length;
}

Object.assign(window, {
  ACCOUNTS, APPS, ACTIVITY,
  getActiveAccount, setActiveAccount, useActiveAccount,
  getSignedIn, setSignedIn, useSignedIn,
  countByBucket, sliceByMuni, sliceByProperty, notifCount,
});
