// Single-user profile model. The Hub is now scoped to ONE owner — no household,
// no members, no invites. Persisted to localStorage.

const HOUSEHOLD = { name: 'Kingsleigh', location: '' };

const SEED_PROFILE = {
  id: 'owner', initial: 'O', useTheme: true,
  name: 'Owner', email: '',
  tz: 'America/Toronto (EST/EDT)',
  theme: 'lime',
  notif: { overdue: true, digest: true, gaps: false, reminders: true, channel: 'Email + Push' },
  calendar: {}, // provider -> connection
};

window.Account = (function () {
  const KEY = 'homehub.profile.v1';
  const LEGACY_KEY = 'homehub.account.v2';

  function load() {
    try { return JSON.parse(localStorage.getItem(KEY)); } catch (e) { return null; }
  }
  // Migrate the old multi-member account snapshot down to just the owner.
  function migrateLegacy() {
    try {
      const old = JSON.parse(localStorage.getItem(LEGACY_KEY));
      if (!old) return null;
      const owner = (old.members || []).find(m => m.role === 'Owner') || (old.members || [])[0];
      if (!owner) return null;
      return {
        id: 'owner', initial: owner.initial || 'O', useTheme: true,
        name: owner.name || 'Owner', email: owner.email || '',
        tz: owner.tz || SEED_PROFILE.tz, theme: owner.theme || 'lime',
        notif: Object.assign({}, SEED_PROFILE.notif, owner.notif || {}),
        calendar: owner.calendar || {},
      };
    } catch (e) { return null; }
  }

  let state = load() || migrateLegacy() || JSON.parse(JSON.stringify(SEED_PROFILE));
  function save() {
    try { localStorage.setItem(KEY, JSON.stringify(state)); } catch (e) {}
    if (window.Cloud && window.Cloud.saveState) window.Cloud.saveState();
  }
  save();

  return {
    KEY,
    current: () => state,
    updateCurrent: (patch) => { Object.assign(state, patch); save(); },
    setCalendar: (provider, conn) => {
      state.calendar = state.calendar || {};
      if (conn) state.calendar[provider] = conn; else delete state.calendar[provider];
      save();
    },
    // Cloud-restore entry point. Replaces local state in place, persists, but
    // does NOT push back to the cloud (would cause a loop).
    replaceFromCloud: (next) => {
      if (!next || typeof next !== 'object') return;
      state = Object.assign(JSON.parse(JSON.stringify(SEED_PROFILE)), next);
      try { localStorage.setItem(KEY, JSON.stringify(state)); } catch (e) {}
    },
    reset: () => {
      try { localStorage.removeItem(KEY); } catch (e) {}
      state = JSON.parse(JSON.stringify(SEED_PROFILE));
      save();
    },
  };
})();

// Profile screen options.
const TZ_OPTIONS = [
  'America/Toronto (EST/EDT)', 'America/New_York (EST/EDT)', 'America/Chicago (CST/CDT)',
  'America/Denver (MST/MDT)', 'America/Los_Angeles (PST/PDT)', 'America/Vancouver (PST/PDT)',
  'UTC', 'Europe/London (GMT/BST)', 'Europe/Paris (CET/CEST)', 'Asia/Tokyo (JST)',
];
const CHANNEL_OPTIONS = ['Email + Push', 'Email only', 'Push only', 'None'];

const CAL_PROVIDERS = [
  { id: 'google',  name: 'Google Calendar',  tint: '#2f6fdb', sub: 'Sync routines into a Google calendar' },
  { id: 'apple',   name: 'Apple Calendar',   tint: '#5b6066', sub: 'Sync via iCloud (.ics subscription)' },
  { id: 'outlook', name: 'Outlook Calendar', tint: '#1f7a6e', sub: 'Sync into Microsoft 365 / Outlook' },
];

// Avatar — solid circle with the owner's initial, used in the sidebar and profile screen.
const Avatar = ({ t, member, size = 40 }) => {
  const m = member || window.Account.current();
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', flex: '0 0 auto',
      background: `linear-gradient(135deg, ${t.accent} 0%, ${t.accentDeep} 100%)`,
      color: t.accentInk,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontWeight: 600, fontSize: Math.round(size * 0.4), letterSpacing: 0.2,
    }}>{(m && m.initial) || 'O'}</div>
  );
};

Object.assign(window, {
  HOUSEHOLD, TZ_OPTIONS, CHANNEL_OPTIONS, CAL_PROVIDERS, Avatar,
});
