const { useState, useEffect, useMemo, useRef } = React;

const NAV = [
  { section: "Analyze" },
  { id: "exec", label: "Executive", icon: "dashboard" },
  { id: "copilot", label: "AI Copilot", icon: "sparkles", badge: "AI" },
  { id: "nlq", label: "Ask VyaparBI", icon: "search" },
  { id: "mlstudio", label: "ML Studio", icon: "brain", badge: "ML" },
  { id: "industry", label: "Industry Analytics", icon: "factory" },
  { id: "builder", label: "Dashboard Builder", icon: "layers" },
  { section: "Data" },
  { id: "sources", label: "Data Sources", icon: "plug" },
  { id: "pipelines", label: "Pipelines & ETL", icon: "workflow" },
  { id: "semantic", label: "Semantic Layer", icon: "scale" },
  { id: "catalog", label: "Data Catalog", icon: "book" },
  { section: "Operate" },
  { id: "geo", label: "Geospatial", icon: "map" },
  { id: "iot", label: "IoT & Real-time", icon: "activity", badge: "LIVE" },
  { id: "twin", label: "Digital Twin", icon: "box" },
  { id: "reports", label: "Reports & Alerts", icon: "bell" },
  { id: "collab", label: "Collaboration", icon: "message" },
  { section: "Govern" },
  { id: "governance", label: "Governance", icon: "shield" },
  { id: "admin", label: "Users & Roles", icon: "users" },
  { section: "Platform" },
  { id: "developer", label: "Developer & APIs", icon: "code" },
  { id: "mobile", label: "Mobile App", icon: "smartphone" },
];

const CRUMBS = {
  exec: ["Analyze", "Executive Dashboard"],
  copilot: ["Analyze", "AI Copilot"],
  nlq: ["Analyze", "Ask VyaparBI"],
  mlstudio: ["Analyze", "ML Studio & Forecasting"],
  industry: ["Analyze", "Industry Analytics"],
  builder: ["Analyze", "Dashboard Builder", "GeM Quarterly Review"],
  sources: ["Data", "Sources"],
  pipelines: ["Data", "Pipelines & ETL"],
  semantic: ["Data", "Semantic Layer"],
  catalog: ["Data", "Catalog & Governance"],
  geo: ["Operate", "Geospatial Analytics"],
  iot: ["Operate", "IoT & Real-time"],
  twin: ["Operate", "Digital Twin"],
  reports: ["Operate", "Reports & Alerts"],
  collab: ["Operate", "Collaboration & Workflow"],
  governance: ["Govern", "Governance & Compliance"],
  admin: ["Govern", "Users & Roles"],
  developer: ["Platform", "Developer & APIs"],
  mobile: ["Platform", "Mobile App"],
};

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "collapsed": false,
  "showCopilot": false,
  "density": "comfortable",
  "accent": "navy-saffron"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(DEFAULTS);
  const [route, setRoute] = useState(() => localStorage.getItem("vbi.route") || "exec");
  const [drawer, setDrawer] = useState(false);

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", t.theme);
  }, [t.theme]);

  useEffect(() => { localStorage.setItem("vbi.route", route); }, [route]);

  const Screen = {
    exec: ExecutiveScreen,
    copilot: CopilotScreen,
    nlq: NLQScreen,
    mlstudio: MLStudioScreen,
    industry: IndustryScreen,
    builder: BuilderScreen,
    sources: SourcesScreen,
    pipelines: PipelinesScreen,
    semantic: SemanticScreen,
    catalog: CatalogScreen,
    geo: GeoScreen,
    iot: IoTScreen,
    twin: TwinScreen,
    reports: ReportsScreen,
    collab: CollabScreen,
    governance: GovernanceScreen,
    admin: AdminScreen,
    developer: DeveloperScreen,
    mobile: MobileScreen,
  }[route] || ExecutiveScreen;

  return (
    <div className="app" data-collapsed={t.collapsed}>
      <aside className="side">
        <div className="brand" onClick={() => setTweak('collapsed', !t.collapsed)} style={{ cursor: 'pointer' }} title="Toggle sidebar">
          <div className="brand-mark">
            <svg viewBox="0 0 24 24" fill="none">
              <rect x="4" y="12" width="3" height="8" rx="1" fill="white"/>
              <rect x="9" y="7" width="3" height="13" rx="1" fill="white" opacity=".85"/>
              <rect x="14" y="4" width="3" height="16" rx="1" fill="#FFD79A"/>
              <circle cx="19.5" cy="5.5" r="2" fill="#FFB84D"/>
            </svg>
          </div>
          <div className="brand-name">
            <span className="dv">व्यापार <span style={{ color: 'var(--primary)' }}>BI</span></span>
            <span className="en">Bharat Intelligence</span>
          </div>
        </div>
        <div className="side-scroll">
          {NAV.map((n, i) => n.section ? (
            <div key={i} className="side-section"><span>{n.section}</span></div>
          ) : (
            <div key={n.id} className={`nav-item ${route === n.id ? 'active' : ''}`} onClick={() => setRoute(n.id)}>
              <Icon name={n.icon} />
              <span className="nav-label">{n.label}</span>
              {n.badge && <span className="nav-badge" style={{ background: n.badge === 'LIVE' ? 'var(--danger)' : 'linear-gradient(135deg, var(--primary), var(--accent))' }}>{n.badge}</span>}
            </div>
          ))}
        </div>
        <div className="side-foot">
          <div className="avatar">AR</div>
          <div className="side-foot-info">
            <div className="n">Aditi Ranganathan</div>
            <div className="r">Admin · IT Central</div>
          </div>
          <div className="cog" onClick={() => setRoute("admin")} title="Settings"><Icon name="settings" size={14}/></div>
        </div>
      </aside>

      <main className="main">
        <header className="topbar">
          <div className="crumbs">
            {(CRUMBS[route] || []).map((c, i, arr) => (
              <React.Fragment key={i}>
                <span className={i === arr.length - 1 ? 'cur' : ''}>{c}</span>
                {i < arr.length - 1 && <Icon name="chevronRight" size={12} className="sep"/>}
              </React.Fragment>
            ))}
          </div>
          <div className="top-search">
            <Icon name="search"/>
            <input placeholder="Search dashboards, datasets, vendors, tenders…" />
            <span className="kbd">⌘K</span>
          </div>
          <div className="top-right">
            <div className="compliance-pill" title="Compliance"><span className="d"/>ISO 27001 · DPDP</div>
            <button className="icon-btn" title="Theme" onClick={() => setTweak('theme', t.theme === 'light' ? 'dark' : 'light')}>
              <Icon name={t.theme === 'light' ? 'moon' : 'sun'}/>
            </button>
            <button className="icon-btn" title="Notifications"><Icon name="bell"/><span className="dot"/></button>
            <button className="copilot-btn" onClick={() => setDrawer(d => !d)}>
              <Icon name="sparkles" className="spark"/>
              Ask AI
              <span className="kbd" style={{ fontSize: 10, marginLeft: 4, padding: '1px 6px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--panel-2)', color: 'var(--ink-3)', fontFamily: 'JetBrains Mono' }}>⌘/</span>
            </button>
          </div>
        </header>

        <Screen setRoute={setRoute} />
      </main>

      {drawer && <CopilotDrawer onClose={() => setDrawer(false)} />}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Appearance">
          <TweakRadio label="Theme" value={t.theme} onChange={v => setTweak('theme', v)} options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }]}/>
          <TweakToggle label="Sidebar collapsed" value={t.collapsed} onChange={v => setTweak('collapsed', v)}/>
        </TweakSection>
        <TweakSection title="AI Copilot">
          <TweakToggle label="Show floating copilot" value={drawer} onChange={setDrawer}/>
        </TweakSection>
        <TweakSuggestionBar suggestions={[
          "Show me the Executive dashboard",
          "Open ML Studio and forecast demand",
          "Show the Digital Twin of the Bhopal substation",
          "Take me to Governance & Compliance",
          "Open the Industry Analytics for Manufacturing",
        ]}/>
      </TweaksPanel>
    </div>
  );
}

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