// Main app

const DEFAULTS = window.__TWEAKS__ || {};

function App(){
  // Auth gate at the top level — App itself only calls one hook so its hook order
  // is stable regardless of auth state. The signed-in dashboard lives in AppShell.
  const auth = window.useUser ? window.useUser() : { user: { email: "dev@local", name: "Dev" }, signOut: () => {} };
  if (!auth.user) return window.SignInScreen ? <window.SignInScreen/> : <div>Loading auth…</div>;
  return <AppShell user={auth.user} signOut={auth.signOut}/>;
}

function AppShell({ user, signOut }){
  const [tweaks, setTweak] = window.useTweaks ? window.useTweaks(DEFAULTS) : [DEFAULTS, ()=>{}];
  const [drawerClient, setDrawerClient] = React.useState(null);
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [addOpen, setAddOpen] = React.useState(false);
  const [addSegment, setAddSegment] = React.useState("md");
  const [navOpen, setNavOpen] = React.useState(false);

  // Persisted-added companies (survive reloads via Store/localStorage).
  // Subscribing here re-renders the App when an entry is added.
  window.useStore(s => s.addedCompanies);
  const persistedMD   = window.Store ? window.Store.getAddedCompanies("md")   : [];
  const persistedMgmt = window.Store ? window.Store.getAddedCompanies("mgmt") : [];

  // Re-hydrate the per-name records into MD_DATA/MGMT_DATA so the existing
  // section/row code (which reads MD_DATA[name]) finds them after reload.
  React.useEffect(() => {
    persistedMD.forEach(c   => { if (!MD_DATA[c.name])   MD_DATA[c.name]   = c.record; });
    persistedMgmt.forEach(c => { if (!MGMT_DATA[c.name]) MGMT_DATA[c.name] = c.record; });
  }, [persistedMD.length, persistedMgmt.length]);

  const openClient = (clientData, opts = {}) => {
    // Optional hints from callers (e.g. AlertsPanel) to land on a specific tab and
    // highlight a specific task. The drawer reads these off the data object.
    setDrawerClient({
      ...clientData,
      _initialTab: opts.initialTab || null,
      _highlightTaskAt: opts.highlightTaskAt || null,
    });
    setDrawerOpen(true);
  };
  const closeDrawer = () => setDrawerOpen(false);

  const onAddCompany = (segment) => {
    setAddSegment(segment);
    setAddOpen(true);
  };
  const handleAdded = ({ segment, name, seed, logo }) => {
    // Build full company record with sensible fallbacks for any unset fields.
    const record = {
      health: seed.health || "green",
      poc: seed.poc,
      champion: seed.champion || undefined,
      lastTouch:{ type:"call", who:"Dr. Yohai", when:"Just added", note:"Client onboarded. First touchpoint pending." },
      currentProject: seed.currentProject,
      services: seed.services && seed.services.length ? seed.services : [],
      openTasks: seed.openTasks ?? 1,
      renewalDays: seed.renewalDays ?? 365,
      renewalDate: seed.renewalDate,
      nextCall: seed.nextCall,
      mrr: seed.mrr,
      opportunity: seed.opportunity,
      contacts: seed.contacts || [],
      tasks: seed.tasks || [],
      timeline: seed.timeline || [],
    };
    if(segment === "md") MD_DATA[name] = record;
    else                 MGMT_DATA[name] = record;
    // Persist the addition + record so it survives page reloads (via localStorage).
    if (window.Store && window.Store.addCompany) {
      window.Store.addCompany(segment, name, record);
    }
    // Persist logo choice as an override so the row + drawer pick it up.
    if(logo && window.Store && window.Store.setCompanyOverride){
      window.Store.setCompanyOverride(name, segment, logo);
    }
  };

  const mdCompaniesSet   = new Set([...(tweaks.mdCompanies   || []), ...persistedMD.map(c=>c.name)]);
  const mgmtCompaniesSet = new Set([...(tweaks.mgmtCompanies || []), ...persistedMgmt.map(c=>c.name)]);
  const mdCompanies   = [...mdCompaniesSet];
  const mgmtCompanies = [...mgmtCompaniesSet];

  // Reveal animations on scroll
  React.useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries)=>{
      entries.forEach(e => { if(e.isIntersecting) e.target.classList.add("in"); });
    }, { threshold:0.12, rootMargin:"0px 0px -40px 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [mdCompanies.length, mgmtCompanies.length]);

  return (
    <div className="app">
      <TopBar onOpenMenu={() => setNavOpen(true)}/>
      <div style={{ position:"fixed", top:14, right:18, zIndex:90 }}>
        {window.UserPill && <window.UserPill user={user} onSignOut={signOut}/>}
      </div>
      <EditorialHeader/>

      {tweaks.showKPIs !== false && <div id="kpis" className="reveal in"><KPIStrip/></div>}

      <FinanceSection/>

      {tweaks.showAlerts !== false && (
        <div id="attention" className="agenda-row reveal in solo">
          <AlertsPanel onOpen={openClient}/>
        </div>
      )}

      <div id="gantt"><GanttCalendar/></div>

      <MDServicesSection
        companies={mdCompanies}
        onOpenClient={openClient}
        onAddCompany={onAddCompany}
        variant={tweaks.rowVariant || "horizon"}
      />

      <ManagementSection
        companies={mgmtCompanies}
        onOpenClient={openClient}
        onAddCompany={onAddCompany}
        variant={tweaks.rowVariant || "horizon"}
      />

      <NewBusinessPipeline onOpenClient={openClient}/>

      <InternalSection/>

      <div className="footer">
        <div>Medical <em style={{color:"var(--accent)",fontStyle:"italic"}}>by Moveo</em> · Control Center</div>
        <div>Synced just now · v1.0</div>
        <div className="footer-duck"><img src="assets/duck-medical.png" alt=""/></div>
      </div>

      <ClientDrawer open={drawerOpen} data={drawerClient} onClose={closeDrawer}/>
      <AddCompanyModal open={addOpen} segment={addSegment} onClose={()=>setAddOpen(false)} onAdd={handleAdded}/>

      {window.MobileNav && <window.MobileNav open={navOpen} onClose={()=>setNavOpen(false)}/>}
      {window.BottomTabBar && <window.BottomTabBar onOpenMenu={()=>setNavOpen(true)}/>}

      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks" initialOpen={false}>
          <window.TweakSection title="Layout">
            <window.TweakRadio
              label="Company row layout"
              value={tweaks.rowVariant || "horizon"}
              options={["horizon","ledger","stack"]}
              onChange={v => setTweak("rowVariant", v)}
            />
          </window.TweakSection>
          <window.TweakSection title="Sections">
            <window.TweakToggle label="Show KPI strip" value={tweaks.showKPIs !== false} onChange={v => setTweak("showKPIs", v)}/>
            <window.TweakToggle label="Show alerts panel" value={tweaks.showAlerts !== false} onChange={v => setTweak("showAlerts", v)}/>
          </window.TweakSection>
          <window.TweakSection title="Density">
            <window.TweakRadio
              label="Tile density"
              value={tweaks.density || "compact"}
              options={["compact","cozy"]}
              onChange={v => setTweak("density", v)}
            />
          </window.TweakSection>
          <window.TweakSection title="Add clients">
            <window.TweakButton label="+ Add MD Service client" onClick={()=>onAddCompany("md")}/>
            <window.TweakButton label="+ Add Management client" onClick={()=>onAddCompany("mgmt")}/>
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
