// CRM Demo — top-level click-through that embeds the REAL prototype screens.
// The demo sidebar controls navigation; each prototype page is shown in a frame
// with its own in-page sidebar/topstrip hidden, so only Home · Accounts · Leads ·
// Opportunities are reachable. Everything else is locked.

const { useState: useDemoState, useRef: useDemoRef, useEffect: useDemoEffect } = React;

const LockIcon = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>
);

// Top-level view → entry page
const PAGE = {
  home:     'CRM Home v2.html',
  accounts: 'CRM Account 360.html',
  leads:    'CRM Lead Capture.html',
  opps:     'CRM Pipeline.html'
};

// Any prototype file → which top-level item should stay highlighted
const FILE_TO_VIEW = {
  'CRM Home v2.html': 'home', 'CRM Home.html': 'home',
  'CRM My Day.html': 'home', 'CRM KPI Tiles.html': 'home', 'CRM Feed.html': 'home',
  'CRM Account 360.html': 'accounts',
  'CRM Lead Capture.html': 'leads',
  'CRM Pipeline.html': 'opps', 'CRM Forecast.html': 'opps',
  'CRM Opportunity Detail.html': 'opps', 'CRM New Opportunity.html': 'opps',
  'CRM Sales Playbook.html': 'opps', 'CRM Win-Loss.html': 'opps',
  'CRM Competitors.html': 'opps'
};

// ── Demo navigation model: which items are live ───────────────
const DEMO_NAV = [
  { group: 'Workspace', items: [
    { id: 'home', icon: 'home', label: 'Home', live: true },
    { id: 'ai',   icon: 'ai',   label: 'AI Assistant', live: false }
  ]},
  { group: 'Sales', items: [
    { id: 'accounts', icon: 'accounts', label: 'Accounts & Contacts', live: true, badge: '1.2k' },
    { id: 'leads',    icon: 'leads',    label: 'Leads',               live: true, badge: '24' },
    { id: 'opps',     icon: 'opps',     label: 'Opportunities',       live: true, badge: '18' },
    { id: 'quotes',   icon: 'quotes',   label: 'Quotes',              live: false },
    { id: 'contracts',icon: 'contracts',label: 'Contracts',           live: false }
  ]},
  { group: 'Engage', items: [
    { id: 'activities', icon: 'activities', label: 'Activities',        live: false, badge: '7' },
    { id: 'service',    icon: 'service',    label: 'Service & Tickets', live: false, badge: '3' },
    { id: 'visits',     icon: 'visits',     label: 'Visit Planning',    live: false }
  ]},
  { group: 'Operate', items: [
    { id: 'territory', icon: 'territory', label: 'Territory & Team',    live: false },
    { id: 'kb',        icon: 'kb',        label: 'Knowledge Base',      live: false },
    { id: 'analytics', icon: 'analytics', label: 'Reports & Analytics', live: false }
  ]},
  { group: 'Configure', items: [
    { id: 'integrations', icon: 'plug',  label: 'Integrations Hub', live: false },
    { id: 'admin',        icon: 'admin', label: 'Admin & Config',   live: false }
  ]}
];

function DemoSidebar({ active, onNav }) {
  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <span style={{display:'flex', alignItems:'center'}}>
          <img src="assets/deepIng-logo.png" alt="deepIng" />
          <span className="crm-tag">CRM</span>
          <span className="demo-pill">Demo</span>
        </span>
      </div>
      <nav className="sidebar-nav">
        {DEMO_NAV.map(g => (
          <React.Fragment key={g.group}>
            <div className="nav-section">{g.group}</div>
            {g.items.map(n => n.live ? (
              <a key={n.id} onClick={() => onNav(n.id)}
                 className={"nav-item demo-enabled" + (n.id === active ? " active" : "")}>
                <span className="ico">{Icons[n.icon]}</span>
                <span>{n.label}</span>
                {n.badge && <span className="badge">{n.badge}</span>}
              </a>
            ) : (
              <span key={n.id} className="nav-item locked" title="In der Vollversion verfügbar">
                <span className="ico">{Icons[n.icon]}</span>
                <span>{n.label}</span>
                {n.badge && <span className="badge">{n.badge}</span>}
                <span className="lock">{LockIcon}</span>
              </span>
            ))}
          </React.Fragment>
        ))}
      </nav>
      <div className="sidebar-foot">
        <div className="avatar">JS</div>
        <div className="user-meta">
          <b>Julia Schmidt</b>
          <span>Sales Rep · DACH</span>
        </div>
      </div>
    </aside>
  );
}

// CSS injected into each embedded page to hide its own chrome
const INJECT_CSS = `
  .topstrip { display: none !important; }
  .sidebar  { display: none !important; }
  .main     { margin-left: 0 !important; margin-top: 0 !important; }
  html, body { background: var(--bg) !important; }
`;

function DemoApp() {
  const [view, setView] = useDemoState('home');
  const [src, setSrc]   = useDemoState(PAGE.home);
  const [loading, setLoading] = useDemoState(true);
  const frameRef = useDemoRef(null);

  const nav = (id) => {
    if (id === view && frameRef.current) {
      // re-click same item → reset to that area's entry page
      setLoading(true);
      setSrc(PAGE[id] + '?t=' + Date.now());
      return;
    }
    setLoading(true);
    setView(id);
    setSrc(PAGE[id]);
  };

  const onFrameLoad = () => {
    const f = frameRef.current;
    if (!f) return;
    try {
      const doc = f.contentDocument;
      // inject chrome-hiding stylesheet (idempotent)
      if (doc && !doc.getElementById('__demo_inject')) {
        const st = doc.createElement('style');
        st.id = '__demo_inject';
        st.textContent = INJECT_CSS;
        doc.head.appendChild(st);
      }
      // keep the correct top-level item highlighted based on the loaded file
      const path = decodeURIComponent((f.contentWindow.location.pathname || '').split('/').pop());
      const mapped = FILE_TO_VIEW[path];
      if (mapped) setView(mapped);
    } catch (e) { /* same-origin expected; ignore */ }
    setLoading(false);
  };

  return (
    <>
      <div className="topstrip"></div>
      <DemoSidebar active={view} onNav={nav} />
      <main className="demo-stage-wrap">
        {loading && (
          <div className="demo-loading">
            <div className="demo-spinner"></div>
          </div>
        )}
        <iframe
          ref={frameRef}
          className="demo-stage"
          src={src}
          title="CRM Demo"
          onLoad={onFrameLoad}
        ></iframe>
      </main>
    </>
  );
}

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