// Vanta App — core: persistent store, logo, shared style helpers.

const VANTA_STORE_KEY = 'vanta.app.v1';

// Local calendar day (not UTC) — the key we scope the day's checkmarks to.
function vantaTodayKey() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

function vantaLoadStore() {
  try {
    const raw = localStorage.getItem(VANTA_STORE_KEY);
    if (!raw) return {};
    const s = JSON.parse(raw);
    // habits/moves/chores are OPTIMISTIC overrides for today only — the server
    // holds the real state and resets it at midnight. If the stored day isn't
    // today, drop them so a new day opens on the server's clean slate instead
    // of yesterday's checkmarks shadowing the reset (that was the "habits stay
    // checked and never reset" bug). Palette, thoughts, order etc. persist.
    if (s.day !== vantaTodayKey()) {
      s.habits = {}; s.moves = {}; s.chores = {};
      s.day = vantaTodayKey();
    }
    return s;
  } catch (e) {}
  return {};
}

const VANTA_DEFAULT_STATE = {
  palette: 'dusk',
  horizon: 'today',
  depth: 'smart',       // garden layering: 'smart' opens what's notable, 'open' shows all
  day: null,            // local calendar day the checks below belong to
  moves: {},            // index -> done (today only)
  habits: {},           // habit name -> done (today only, overrides server)
  chores: {},           // chore name -> done (today only)
  thoughts: [],         // [{ text, ts }]
  linked: { finance: false, sleep: true, health: false, vault: false },
  lastTouch: {},        // areaKey -> ts (ms)
  hidden: { health: true },  // areaKey -> hidden
};

function useVantaStore() {
  const [state, setState] = React.useState(() => {
    const merged = { ...VANTA_DEFAULT_STATE, ...vantaLoadStore() };
    if (!merged.day) merged.day = vantaTodayKey();
    return merged;
  });
  const update = React.useCallback((patch) => {
    setState(prev => {
      const next = typeof patch === 'function' ? { ...prev, ...patch(prev) } : { ...prev, ...patch };
      try { localStorage.setItem(VANTA_STORE_KEY, JSON.stringify(next)); } catch (e) {}
      return next;
    });
  }, []);
  return [state, update];
}

// Relative time, quietly worded.
function vantaAgo(ts) {
  if (!ts) return null;
  const s = Math.floor((Date.now() - ts) / 1000);
  if (s < 60) return 'just now';
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  const d = Math.floor(h / 24);
  return `${d}d ago`;
}

// Rotating monogram — a vanta-black V. The one color that never follows
// the palette: vanta black absorbs everything. On dark grounds it keeps a
// hairline of ink so the absorbing shape still reads.
function VantaM({ P, size = 26, fontSize = 22 }) {
  const dark = parseInt((P?.bg || '#fff').slice(1, 3), 16) < 80;
  return (
    <span className="vanta-m" style={{
      display: 'grid', placeItems: 'center', width: size, height: size,
      fontFamily: '"Newsreader", serif', fontWeight: 600, fontSize,
      color: '#050505', lineHeight: 1,
      WebkitTextStroke: dark ? `0.8px ${P.ink3}` : undefined,
    }}>V</span>
  );
}

function vStyles(P) {
  return {
    num: { fontFamily: '"Bricolage Grotesque", sans-serif', fontFeatureSettings: '"tnum" 1', fontVariationSettings: '"wdth" 90', letterSpacing: '-0.02em' },
    serif: { fontFamily: '"Instrument Serif", "Newsreader", serif', fontStyle: 'italic', fontWeight: 400, letterSpacing: '-0.01em' },
    caps: { fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: P.ink3, fontWeight: 500 },
  };
}

const V_TILE_BG = (P, k) => ({
  health: P.tileWarm, sleep: P.tileSky, thoughts: P.tilePink,
  finance: P.tile, work: P.tile, professional: P.tilePink,
  learning: P.tileWarm, home: P.tileCool, hobbies: P.tileMoss, habits: P.tileMoss,
})[k] || P.tile;
const V_RING = (P, k) => ({
  health: P.rust, sleep: P.sky, thoughts: P.rust,
  finance: P.accent, work: P.ink, professional: P.rust,
  learning: P.accent, home: P.sky, hobbies: P.accent, habits: P.accent,
})[k] || P.accent;

// Data-source metadata per area — shown only in the drill-in.
const V_SOURCES = {
  sleep:        { kind: 'synced', label: 'sleep app · pushed', manual: true },
  thoughts:     { kind: 'manual', label: 'planted by you · vault sync planned' },
  finance:      { kind: 'connect', label: 'not linked · plaid, read-only' },
  health:       { kind: 'connect', label: 'watch not connected' },
  work:         { kind: 'manual', label: 'logged by you' },
  learning:     { kind: 'manual', label: 'logged by you' },
  professional: { kind: 'manual', label: 'logged by you' },
  hobbies:      { kind: 'manual', label: 'logged by you' },
  habits:       { kind: 'manual', label: 'checked by you' },
  home:         { kind: 'manual', label: 'logged by you' },
  goals:        { kind: 'manual', label: 'reviewed monthly' },
};

Object.assign(window, {
  useVantaStore, vantaAgo, VantaM, vStyles, V_TILE_BG, V_RING, V_SOURCES,
});
