/* ============================================================
   Lectual CRM — app shell, router, tweaks, mount
   ============================================================ */

/* Optional per-deployment overrides — set these globals before this file
   loads (e.g. rpb-data.js) to re-skin the shell. Defaults preserve the
   original Lectual / Dana Whitfield behavior exactly. */
const TWEAK_DEFAULTS = window.LECTUAL_TWEAK_DEFAULTS || /*EDITMODE-BEGIN*/{
  "firm": "lectual",
  "dark": false,
  "tone": "plain"
}/*EDITMODE-END*/;

const USER = window.LECTUAL_USER || { initials: 'DW', name: 'Dana Whitfield', role: 'Trademark attorney', first: 'Dana' };
const NAV_BADGES = window.LECTUAL_NAV_BADGES || { pipeline: '8', agents: '3' };
const FIRM = window.LECTUAL_FIRM || null;

const NAV = [
  { id: 'home',     label: 'Today',      icon: I.today },
  { id: 'pipeline', label: 'Pipeline',   icon: I.pipe, badge: NAV_BADGES.pipeline },
  { id: 'lead',     label: 'Leads',      icon: I.leads },
  { id: 'agents',   label: 'Agents',     icon: I.agent, badge: NAV_BADGES.agents },
  { id: 'copilot',  label: 'AI Copilot', icon: I.copilot, soon: true },
  { id: 'market',   label: 'Marketing',  icon: I.market, soon: true },
  { id: 'reports',  label: 'Reports',    icon: I.reports, soon: true },
  { id: 'admin',    label: 'Admin',      icon: I.admin, soon: true },
];

const TITLES = {
  home:     { eyebrow: 'Operations', title: 'Today' },
  pipeline: { eyebrow: 'Pipeline', title: 'Intake → client pipeline' },
  lead:     { eyebrow: 'Pipeline · Lead', title: 'Lead detail' },
  agents:   { eyebrow: 'Automation', title: 'Agents' },
};

function Rail({ view, go, firm, pushToast }) {
  const th = THEMES[firm];
  return (
    <div className="rail">
      <div className="brand"><Echo size={18} /></div>
      <div className="firmbadge">
        <span className="fb-logo">{FIRM?.logo ?? th.logo}</span>
        <div className="fb-meta"><div className="fb-name">{FIRM?.name ?? th.name}</div><div className="fb-tier">{FIRM?.tier ?? th.tier}</div></div>
      </div>
      {NAV.filter((n) => !n.soon).map((n) => (
        <a key={n.id} className={view === n.id ? 'on' : ''} onClick={() => go(n.id)}>{n.icon} {n.label}{n.badge && <span className="badge">{n.badge}</span>}</a>
      ))}
      <div className="seg">Workspace</div>
      {NAV.filter((n) => n.soon).map((n) => (
        <a key={n.id} onClick={() => pushToast(n.label + ' arrives in the next build pass')} style={{ opacity: .62 }}>{n.icon} {n.label}<span className="badge" style={{ background: 'transparent', border: '1px solid rgba(255,255,255,.18)', fontSize: 8 }}>SOON</span></a>
      ))}
      <div className="me"><div className="mav">{USER.initials}</div><div><div className="nm">{USER.name}</div><div className="ro">{USER.role}</div></div></div>
    </div>
  );
}

function Topbar({ view, leadId, go }) {
  const t = TITLES[view] || TITLES.home;
  const lead = LEADS_ALL.find((l) => l.id === leadId);
  const title = view === 'lead' && lead ? lead.name : t.title;
  return (
    <div className="topbar">
      {view === 'lead' && (
        <button className="iconbtn" onClick={() => go('pipeline')} aria-label="Back" style={{ marginRight: -4 }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M15 6l-6 6 6 6" /></svg>
        </button>
      )}
      <div>
        <div className="eyebrow">{t.eyebrow}</div>
        <h1>{title}</h1>
      </div>
      <div className="sp" />
      <div className="search">{I.search}<input placeholder="Search leads, marks, tasks…" /></div>
      <button className="iconbtn" aria-label="Notifications">{I.bell}<span className="ndot" /></button>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useState('home');
  const [leadId, setLeadId] = useState((window.LECTUAL_LEADS[0] || {}).id || 'maya');
  const [toasts, pushToast] = useToasts();

  useEffect(() => { applyTheme(t.firm, t.dark); }, [t.firm, t.dark]);

  const go = useCallback((v, id) => {
    if (id) setLeadId(id);
    setView(v);
    document.querySelector('.scrollarea, .center')?.scrollTo?.(0, 0);
  }, []);

  return (
    <div className="app">
      <Rail view={view} go={go} firm={t.firm} pushToast={pushToast} />
      <div className="main">
        <Topbar view={view} leadId={leadId} go={go} />
        {view === 'home' && <OpsHome go={go} pushToast={pushToast} tone={t.tone} />}
        {view === 'pipeline' && <Pipeline go={go} pushToast={pushToast} />}
        {view === 'lead' && <LeadDetail leadId={leadId} go={go} pushToast={pushToast} />}
        {view === 'agents' && <AgentsView go={go} pushToast={pushToast} />}
      </div>

      <Toaster toasts={toasts} />

      <TweaksPanel>
        <TweakSection label="Firm theme" hint="Every accent reads from --firm-* tokens. Switching re-skins the whole CRM — no hardcoded brand color." />
        <TweakSelect label="Tenant" value={t.firm}
          options={[
            { value: 'lectual', label: 'Lectual (platform)' },
            { value: 'rpb', label: 'Rivera Park (warm / serif)' },
            { value: 'meridian', label: 'Meridian (cool / navy)' },
          ]}
          onChange={(v) => setTweak('firm', v)} />
        <TweakToggle label="Dark mode" value={t.dark} onChange={(v) => setTweak('dark', v)} />
        <TweakSection label="Voice" />
        <TweakRadio label="Briefing tone" value={t.tone} options={['plain', 'warm', 'direct']} onChange={(v) => setTweak('tone', v)} />
      </TweaksPanel>
    </div>
  );
}

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