/* ClinicFlow AI — main App shell. */

const { useState, useEffect } = React;

const NAV_SECTIONS = [
  {
    title: 'Workspace',
    items: [
      { id: 'dashboard',    label: 'Dashboard',     icon: I.layout },
      { id: 'patients',     label: 'Patients',      icon: I.users },
      { id: 'appointments', label: 'Appointments',  icon: I.calendar },
    ]
  },
  {
    title: 'AI · WhatsApp',
    items: [
      { id: 'followups',      label: 'Follow-ups',   icon: I.zap, badge: 6 },
      { id: 'communications', label: 'Communications', icon: I.message },
      { id: 'analytics',      label: 'Analytics',    icon: I.chart },
    ]
  },
  {
    title: 'Configure',
    items: [
      { id: 'settings', label: 'Settings', icon: I.settings },
    ]
  }
];

const PAGE_TITLES = {
  dashboard: 'Dashboard',
  patients: 'Patients',
  profile: 'Patient Profile',
  appointments: 'Appointments',
  followups: 'AI Follow-ups',
  analytics: 'Analytics',
  communications: 'Communications',
  settings: 'Settings',
};

function Sidebar({ route, navigate, density, clinic, open, onClose }) {
  return (
    <aside className={`sidebar ${open ? 'open' : ''}`} data-screen-label="Sidebar">
      <div className="sidebar-brand">
        <span className="sidebar-brand-mark"><OrbisMark size={32} /></span>
        <div>
          <div className="sidebar-brand-text">
            ClinicFlow
            <small>{clinic ? clinic.code + ' · ' + (clinic.role || 'Workspace') : 'AI · v2.4'}</small>
          </div>
        </div>
      </div>

      <div className="sidebar-nav" style={{ paddingTop: 12 }}>
        {NAV_SECTIONS.map((sec, si) => (
          <div key={si}>
            {density !== 'compact' && (
              <div className="sidebar-section-label">{sec.title}</div>
            )}
            {sec.items.map(item => (
              <button
                key={item.id}
                className={`nav-item ${route === item.id ? 'active' : ''}`}
                onClick={() => { navigate(item.id); onClose?.(); }}
                data-screen-label={`Nav: ${item.label}`}
              >
                <span className="icon"><item.icon size={16}/></span>
                {item.label}
                {item.badge && <span className="nav-item-badge">{item.badge}</span>}
              </button>
            ))}
          </div>
        ))}
      </div>

      <div className="sidebar-footer">
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            width: 26, height: 26, borderRadius: 6,
            background: 'linear-gradient(135deg, var(--purple-50), var(--purple-100))',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <OrbisMark size={18} />
          </div>
          <div style={{ lineHeight: 1.3 }}>
            <div style={{ fontSize: 10, color: 'var(--gray-400)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600 }}>Powered by</div>
            <a href="#" style={{ color: 'var(--purple-600)', fontWeight: 600, fontSize: 11 }}>Orbis Systems</a>
          </div>
        </div>
      </div>
    </aside>
  );
}

function Topbar({ route, patientId, navigate, onSearch, onNotif, clinic, user, onSwitchClinic, onSignOut, onMenu }) {
  const [clinicOpen, setClinicOpen] = useState(false);
  const [userOpen, setUserOpen] = useState(false);

  const title = route === 'profile'
    ? (window.CF_DATA.PATIENTS.find(p => p.id === patientId)?.name || 'Patient')
    : PAGE_TITLES[route];

  return (
    <header className="topbar">
      <button className="mobile-menu-btn" onClick={onMenu} title="Menu">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <line x1="3" y1="6" x2="21" y2="6"/>
          <line x1="3" y1="12" x2="21" y2="12"/>
          <line x1="3" y1="18" x2="21" y2="18"/>
        </svg>
      </button>
      <div>
        <div className="topbar-title">{title}</div>
      </div>
      <div className="topbar-right">
        <button className="topbar-icon-btn" title="Search (⌘K)" onClick={onSearch}>
          <I.search size={16} />
        </button>
        <button className="topbar-icon-btn" title="Notifications" onClick={onNotif}>
          <I.bell size={16} />
          <span className="dot"/>
        </button>

        <div className="menu-anchor">
          <button className="clinic-chip" onClick={() => setClinicOpen(o => !o)}>
            <span className="clinic-chip-dot" style={{ background: clinic?.bg || 'linear-gradient(135deg, var(--indigo-500), var(--purple-600))' }}>
              {clinic?.code || 'AF'}
            </span>
            {clinic?.name || 'Apollo Family Clinic'}
            <I.chevDown size={12} stroke="#9CA3AF"/>
          </button>
          <Menu open={clinicOpen} onClose={() => setClinicOpen(false)} style={{ minWidth: 280 }}>
            <div className="menu-label">Current workspace</div>
            <div style={{ padding: '4px 10px 10px', borderBottom: '1px solid var(--border-strong)', marginBottom: 6 }}>
              <div className="flex items-center gap-2">
                <span className="clinic-chip-dot" style={{ width: 28, height: 28, fontSize: 11, background: clinic?.bg }}>{clinic?.code}</span>
                <div style={{ lineHeight: 1.3 }}>
                  <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink)' }}>{clinic?.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--gray-500)' }}>{clinic?.city} · {clinic?.role}</div>
                </div>
              </div>
            </div>
            <button className="menu-item" onClick={() => { setClinicOpen(false); onSwitchClinic(); }}>
              <span className="menu-icon"><I.refresh size={14}/></span>
              Switch workspace
            </button>
            <button className="menu-item" onClick={() => { setClinicOpen(false); navigate('settings'); }}>
              <span className="menu-icon"><I.settings size={14}/></span>
              Workspace settings
            </button>
            <div className="menu-sep"/>
            <button className="menu-item" onClick={() => { setClinicOpen(false); window.toast('Setup wizard coming soon', { type: 'info' }); }}>
              <span className="menu-icon"><I.plus size={14}/></span>
              Add another clinic
            </button>
          </Menu>
        </div>

        <div className="menu-anchor">
          <button className="topbar-avatar" title={user?.name} onClick={() => setUserOpen(o => !o)}>{user?.initials || 'VR'}</button>
          <Menu open={userOpen} onClose={() => setUserOpen(false)} style={{ minWidth: 240 }}>
            <div style={{ padding: '8px 10px 12px', borderBottom: '1px solid var(--border-strong)', marginBottom: 6 }}>
              <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink)' }}>{user?.name || 'Dr. Vimal Rao'}</div>
              <div style={{ fontSize: 12, color: 'var(--gray-500)', marginTop: 2 }} className="mono">{user?.email || 'user@clinic.com'}</div>
            </div>
            <button className="menu-item" onClick={() => { setUserOpen(false); navigate('settings'); }}>
              <span className="menu-icon"><I.user size={14}/></span>My profile
            </button>
            <button className="menu-item" onClick={() => { setUserOpen(false); navigate('settings'); }}>
              <span className="menu-icon"><I.settings size={14}/></span>Workspace settings
            </button>
            <button className="menu-item" onClick={() => { setUserOpen(false); window.toast('Keyboard shortcuts panel — coming soon', { type: 'info' }); }}>
              <span className="menu-icon"><I.list size={14}/></span>Keyboard shortcuts
            </button>
            <div className="menu-sep"/>
            <button className="menu-item" onClick={() => window.toast('Help center coming soon', { type: 'info' })}>
              <span className="menu-icon"><I.message size={14}/></span>Help & support
            </button>
            <button className="menu-item" onClick={() => { setUserOpen(false); onSignOut(); }}>
              <span className="menu-icon"><I.arrowRight size={14}/></span>Sign out
            </button>
          </Menu>
        </div>
      </div>
    </header>
  );
}

// --------------------- App ---------------------
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#7C3AED",
  "density": "comfortable",
  "showAIBadges": true
}/*EDITMODE-END*/;

function AppInner() {
  // Auth state machine: 'login' -> 'picker' -> 'app'
  // Persisted in localStorage so refresh doesn't kick you out
  const [user, setUser] = useState(() => {
    try { return JSON.parse(localStorage.getItem('cf_user') || 'null'); } catch { return null; }
  });
  const [clinic, setClinic] = useState(() => {
    try {
      const id = localStorage.getItem('cf_clinic');
      return id ? window.CLINICS.find(c => c.id === id) || null : null;
    } catch { return null; }
  });

  const [route, setRoute] = useState('dashboard');
  const [patientId, setPatientId] = useState(null);
  const [searchOpen, setSearchOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const [addPatientOpen, setAddPatientOpen] = useState(false);
  const [addApptOpen, setAddApptOpen] = useState(false);
  const [composeFor, setComposeFor] = useState(null);
  const [editFu, setEditFu] = useState(null);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  const handleLogin = (u) => {
    setUser(u);
    try { localStorage.setItem('cf_user', JSON.stringify(u)); } catch {}
    window.toast(`Welcome, ${u.name.split(' ')[0]}`, { sub: 'Pick a workspace to continue', type: 'success' });
  };
  const handlePickClinic = (c) => {
    setClinic(c);
    try { localStorage.setItem('cf_clinic', c.id); } catch {}
    setRoute('dashboard');
    window.toast(`Opened ${c.name}`, { type: 'success' });
  };
  const handleSwitchClinic = () => {
    setClinic(null);
    try { localStorage.removeItem('cf_clinic'); } catch {}
  };
  const handleSignOut = () => {
    setClinic(null);
    setUser(null);
    try { localStorage.removeItem('cf_clinic'); localStorage.removeItem('cf_user'); } catch {}
    window.toast('Signed out', { type: 'info' });
  };

  const navigate = (id, pid) => {
    setRoute(id);
    if (id === 'profile') setPatientId(pid);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  // Cmd/Ctrl + K → search (only when logged in & in a clinic)
  useEffect(() => {
    const onKey = (e) => {
      if (user && clinic && (e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {
        e.preventDefault();
        setSearchOpen(true);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [user, clinic]);

  // Tweaks state — uses the starter hook (returns [values, setTweak] tuple)
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  // Live-apply accent color
  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty('--brand', t.accent);
    r.style.setProperty('--purple-600', t.accent);
  }, [t.accent]);

  useEffect(() => {
    document.documentElement.style.setProperty('--ai-badge-display', t.showAIBadges ? 'inline-flex' : 'none');
  }, [t.showAIBadges]);

  // --- Routing through auth states ---
  if (!user) {
    return <window.LoginPage onLogin={handleLogin} />;
  }
  if (!clinic) {
    return <window.ClinicPickerPage user={user} onPick={handlePickClinic} onSignOut={handleSignOut} />;
  }

  // Shared action handlers passed into pages
  const actions = {
    openCompose: (patient) => setComposeFor(patient),
    openEditFollowup: (item) => setEditFu(item),
    addPatient: () => setAddPatientOpen(true),
    addAppt: () => setAddApptOpen(true),
    toast: (msg, opts) => window.toast(msg, opts),
  };

  return (
    <div className="app" data-density={t.density} data-screen-label={`Page: ${PAGE_TITLES[route]}`}>
      <div className={`sidebar-backdrop ${mobileMenuOpen ? 'show' : ''}`} onClick={() => setMobileMenuOpen(false)} />
      <Sidebar route={route} navigate={navigate} density={t.density} clinic={clinic}
        open={mobileMenuOpen} onClose={() => setMobileMenuOpen(false)} />
      <main>
        <Topbar route={route} patientId={patientId} navigate={navigate}
          onSearch={() => setSearchOpen(true)}
          onNotif={() => setNotifOpen(true)}
          clinic={clinic} user={user}
          onSwitchClinic={handleSwitchClinic}
          onSignOut={handleSignOut}
          onMenu={() => setMobileMenuOpen(true)} />
        <div className="page" key={route + clinic.id}>
          {route === 'dashboard'     && <DashboardPage     navigate={navigate} actions={actions} />}
          {route === 'patients'      && <PatientsPage      navigate={navigate} actions={actions} />}
          {route === 'profile'       && <PatientProfilePage patientId={patientId} navigate={navigate} actions={actions} />}
          {route === 'appointments'  && <AppointmentsPage  actions={actions} />}
          {route === 'followups'     && <FollowUpsPage     actions={actions} />}
          {route === 'analytics'     && <AnalyticsPage     />}
          {route === 'communications'&& <CommunicationsPage actions={actions} />}
          {route === 'settings'      && <SettingsPage      />}
        </div>
      </main>

      {/* Tweaks Panel */}
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection label="Branding">
          <window.TweakColor
            label="Accent color"
            value={t.accent}
            options={['#7C3AED', '#4F46E5', '#0D9488', '#0EA5E9', '#E11D48']}
            onChange={v => setTweak('accent', v)}
          />
        </window.TweakSection>
        <window.TweakSection label="Layout">
          <window.TweakRadio
            label="Sidebar density"
            value={t.density}
            options={[
              { value: 'comfortable', label: 'Comfortable' },
              { value: 'compact', label: 'Compact' },
            ]}
            onChange={v => setTweak('density', v)}
          />
        </window.TweakSection>
        <window.TweakSection label="AI">
          <window.TweakToggle
            label="Show AI badges"
            value={t.showAIBadges}
            onChange={v => setTweak('showAIBadges', v)}
          />
        </window.TweakSection>
        <window.TweakSection label="Jump to page">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
            {Object.keys(PAGE_TITLES).filter(k => k !== 'profile').map(k => (
              <button key={k} className="chip" onClick={() => navigate(k)} style={{
                borderColor: route === k ? 'var(--purple-600)' : '',
                color: route === k ? 'var(--purple-600)' : '',
                background: route === k ? 'var(--purple-50)' : '',
              }}>
                {PAGE_TITLES[k]}
              </button>
            ))}
          </div>
        </window.TweakSection>
      </window.TweaksPanel>

      {/* Overlays */}
      <NotificationsPanel open={notifOpen} onClose={() => setNotifOpen(false)} />
      <SearchOverlay open={searchOpen} onClose={() => setSearchOpen(false)} navigate={navigate} />
      <AddPatientModal open={addPatientOpen} onClose={() => setAddPatientOpen(false)}
        onSave={(p) => window.toast(`Patient added: ${p.name}`, { sub: 'Welcome message queued via WhatsApp' })} />
      <AddAppointmentModal open={addApptOpen} onClose={() => setAddApptOpen(false)}
        onSave={(a) => window.toast(`Appointment scheduled`, { sub: `${a.patient} · ${a.date} at ${a.time}` })} />
      <ComposeModal open={!!composeFor} onClose={() => setComposeFor(null)} patient={composeFor} />
      <EditFollowupModal open={!!editFu} onClose={() => setEditFu(null)} item={editFu}
        onSave={(updated) => { window.cfMutateFollowup?.(updated); }} />
    </div>
  );
}

function App() {
  // Welcome loader plays once per browser session — restored after refresh,
  // bypassed when navigating within the same session.
  const [bootstrapped, setBootstrapped] = useState(() => {
    try { return sessionStorage.getItem('cf_booted') === '1'; } catch { return false; }
  });

  useEffect(() => {
    // Initialize global click-spark effect once
    window.initClickSparks?.();
  }, []);

  if (!bootstrapped) {
    return (
      <window.WelcomeLoader onDone={() => {
        try { sessionStorage.setItem('cf_booted', '1'); } catch {}
        setBootstrapped(true);
      }} />
    );
  }
  return (
    <ToastHost>
      <AppInner />
    </ToastHost>
  );
}

// Hide AI badges via runtime CSS var
const aiCSS = document.createElement('style');
aiCSS.textContent = `.ai-badge { display: var(--ai-badge-display, inline-flex); }`;
document.head.appendChild(aiCSS);

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