/* =========================================================
   home-data.jsx — single source of truth for the CoordOS office home

   Loaded BEFORE home.jsx and main.jsx. Exposes:
     window.HomeData         live mutable store
     window.useHomeData()    React hook (forces re-render on notify)
   ========================================================= */

(function () {
  const subscribers = new Set();

  const initialAttention = [
    {
      id: "a1",
      crewId: "takeoff",
      kind: "budget",
      tag: "Review needed",
      title: "3 trade quotes came in over budget on the Oakwood Residence.",
      money: "$18,450 over target",
      reasoning:
        "Takeoff Reader priced the plan from your rules. Trade Coordinator got real quotes back from Apex Electric and Summit HVAC, and both came in higher than your target.",
      why: [
        "Apex Electric quote: $42,300 vs $39,000 target",
        "Summit HVAC quote: $28,150 vs $26,000 target",
        "Drywall quote is still pending",
      ],
      cta: "Review & Approve",
    },
    {
      id: "a2",
      crewId: "sched",
      kind: "input",
      tag: "Question for you",
      title: "Confirm cabinet allowance for Ridgeview Home.",
      reasoning:
        "Client Liaison has the homeowner update drafted, but Scheduler needs the allowance level before the next 60 days of milestones are final.",
      why: ["Standard allowance: $18k", "Premium allowance: $26k"],
      cta: "Answer Question",
    },
  ];

  const baseCrew = [
    { id: "books",   name: "Bookkeeper",     avatar: "/app/uploads/avatar-books.jpg" },
    { id: "field",   name: "Field Intake",   avatar: "/app/uploads/avatar-field.jpg" },
    { id: "client",  name: "Client Liaison", avatar: "/app/uploads/avatar-client.jpg" },
    { id: "time",    name: "Timekeeper",     avatar: "/app/uploads/avatar-time.jpg" },
    { id: "takeoff", name: "Takeoff Reader", avatar: "/app/uploads/avatar-takeoff.jpg" },
    { id: "sched",   name: "Scheduler",      avatar: "/app/uploads/avatar-sched.jpg" },
  ];

  function deriveCrewStatuses(attentionItems) {
    const needsReview = new Set(attentionItems.map((a) => a.crewId).filter(Boolean));
    return baseCrew.map((c) => ({ ...c, status: needsReview.has(c.id) ? "review" : "working" }));
  }

  const initialActivity = [
    { id: "act1", icon: "quote",   label: "Apex Electric quote folded into Oakwood budget", minutesAgo: 8 },
    { id: "act2", icon: "invoice", label: "ABC Supply bill coded and ready for QuickBooks", minutesAgo: 23 },
    { id: "act3", icon: "log",     label: "Marco's voice note became the Oakwood daily log", minutesAgo: 60 },
    { id: "act4", icon: "mail",    label: "Ridgeview homeowner update drafted",            minutesAgo: 120 },
  ];

  const initialProjects = [
    { id: "p1", name: "Oakwood Residence",   type: "Custom Home", status: "On Schedule",     budgetPct: 92, thumb: "/app/uploads/proj-oakwood.jpg" },
    { id: "p2", name: "Ridgeview Home",      type: "Custom Home", status: "On Schedule",     budgetPct: 89, thumb: "/app/uploads/proj-ridgeview.jpg" },
    { id: "p3", name: "Lakeside Renovation", type: "Renovation",  status: "Slightly Behind", budgetPct: 76, thumb: "/app/uploads/proj-lakeside.jpg" },
  ];

  const HomeData = {
    user: { name: "Jon" },
    stats: { handledOvernight: 27, projectsOnTrack: 6, overdue: 0 },
    attentionItems: initialAttention.slice(),
    crew: deriveCrewStatuses(initialAttention),
    activity: initialActivity.slice(),
    projects: initialProjects.slice(),

    subscribe(fn) {
      subscribers.add(fn);
      return () => subscribers.delete(fn);
    },
    notify() {
      subscribers.forEach((fn) => {
        try { fn(); } catch (err) { /* keep other subscribers alive */ }
      });
    },

    resolveAttention(id) {
      const next = HomeData.attentionItems.filter((a) => a.id !== id);
      HomeData.attentionItems = next;
      HomeData.crew = deriveCrewStatuses(next);
      HomeData.notify();
    },

    reopenDemo() {
      HomeData.attentionItems = initialAttention.slice();
      HomeData.crew = deriveCrewStatuses(HomeData.attentionItems);
      HomeData.activity = initialActivity.slice();
      HomeData.notify();
    },

    advanceClock() {
      HomeData.activity = HomeData.activity.map((a) => ({ ...a, minutesAgo: a.minutesAgo + 1 }));
      HomeData.notify();
    },
  };

  window.HomeData = HomeData;

  /* React hook — components call this to subscribe + read live data */
  window.useHomeData = function useHomeData() {
    const [, setTick] = React.useState(0);
    React.useEffect(() => HomeData.subscribe(() => setTick((t) => t + 1)), []);
    return HomeData;
  };

  /* Presenter shortcut: Shift+R restores the Needs-Attention demo state */
  if (typeof window !== "undefined") {
    window.addEventListener("keydown", (e) => {
      if (e.shiftKey && (e.key === "R" || e.key === "r") && !e.metaKey && !e.ctrlKey && !e.altKey) {
        const tag = e.target && e.target.tagName;
        if (tag === "INPUT" || tag === "TEXTAREA") return;
        e.preventDefault();
        HomeData.reopenDemo();
      }
    });

    /* Tick activity timestamps every minute so the demo feels live */
    window.setInterval(() => HomeData.advanceClock(), 60 * 1000);
  }
})();
