// Shell: sidebar, topbar, status pill, primitive bits used across views.

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

// --- Process documentation rubric -------------------------------------------
// Shared definition used by computeReadiness (in each data file) and display
// components (RubricBreakdown in workflows.jsx). Each criterion is scored 0–3.
window.PROCESS_RUBRIC_DEF = [
  {
    id: 'sop_exists',
    label: 'SOP / procedure exists',
    tiers: [
      'No written procedure of any kind',
      'Informal notes or partial checklist',
      'Structured document, incomplete',
      'Complete controlled SOP with version history',
    ]
  },
  {
    id: 'steps_complete',
    label: 'Steps sequential & complete',
    tiers: [
      'No steps documented',
      'Key steps only, major gaps',
      'Most steps enumerated in order',
      'All steps documented in full sequence',
    ]
  },
  {
    id: 'step_detail',
    label: 'Step detail quality',
    tiers: [
      'Steps listed without context',
      'Some steps include context',
      'Most steps have adequate detail',
      'Every step executable without coaching',
    ]
  },
  {
    id: 'exceptions',
    label: 'Exception & edge case handling',
    tiers: [
      'No exceptions documented',
      'One or two cases noted informally',
      'Main exception paths mapped',
      'Full exception tree with escalation routes',
    ]
  },
  {
    id: 'systems',
    label: 'Systems & tools identified',
    tiers: [
      'No systems specified',
      'Systems mentioned at process level',
      'Most systems identified, some gaps',
      'All systems specified at step level',
    ]
  },
  {
    id: 'roles',
    label: 'Roles & responsibilities',
    tiers: [
      'No roles defined',
      'Process owner identified only',
      'Owners and approvers named',
      'Full RACI or step-level assignments',
    ]
  },
  {
    id: 'io',
    label: 'Inputs & outputs defined',
    tiers: [
      'Neither inputs nor outputs documented',
      'Either inputs or outputs defined',
      'Both defined at process level',
      'I/O defined per step or per variant',
    ]
  },
  {
    id: 'trigger',
    label: 'Trigger conditions',
    tiers: [
      'No trigger documented',
      'General trigger described',
      'Trigger with conditions specified',
      'Trigger, frequency, and conditions fully specified',
    ]
  },
];

// --- tiny inline lucide-style icons (single-purpose SVGs) -------------------
const Icon = ({ d, size = 16, stroke = 1.6, className = "", style }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth={stroke} strokeLinecap="round"
       strokeLinejoin="round" className={className} style={style}>
    {d}
  </svg>
);
const IconSparkles = (p) => <Icon {...p} d={<>
  <path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6z"/>
  <path d="M19 14l.7 1.8L21.5 16.5l-1.8.7L19 19l-.7-1.8L16.5 16.5l1.8-.7z"/>
</>} />;
const IconTable = (p) => <Icon {...p} d={<>
  <rect x="3" y="4" width="18" height="16" rx="1.5"/>
  <path d="M3 10h18M9 4v16"/>
</>} />;
const IconMatrix = (p) => <Icon {...p} d={<>
  <path d="M4 20V4M4 20h16"/>
  <circle cx="9" cy="15" r="1.4"/>
  <circle cx="14" cy="10" r="2"/>
  <circle cx="17" cy="6" r="1"/>
</>} />;
const IconRoadmap = (p) => <Icon {...p} d={<>
  <path d="M4 6h12M4 12h16M4 18h9"/>
  <circle cx="19" cy="6" r="1.2"/>
  <circle cx="14" cy="18" r="1.2"/>
</>} />;
const IconArrowRight = (p) => <Icon {...p} d={<>
  <path d="M5 12h14M13 6l6 6-6 6"/>
</>} />;
const IconArrowUpRight = (p) => <Icon {...p} d={<>
  <path d="M7 17L17 7M9 7h8v8"/>
</>} />;
const IconChevronDown = (p) => <Icon {...p} d={<><path d="M6 9l6 6 6-6"/></>} />;
const IconChevronUp = (p) => <Icon {...p} d={<><path d="M6 15l6-6 6 6"/></>} />;
const IconX = (p) => <Icon {...p} d={<><path d="M18 6L6 18M6 6l12 12"/></>} />;
const IconSearch = (p) => <Icon {...p} d={<><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></>} />;
const IconDownload = (p) => <Icon {...p} d={<><path d="M12 3v12M7 10l5 5 5-5M5 21h14"/></>} />;
const IconShare = (p) => <Icon {...p} d={<><circle cx="6" cy="12" r="2.4"/><circle cx="18" cy="6" r="2.4"/><circle cx="18" cy="18" r="2.4"/><path d="M8 11l8-4M8 13l8 4"/></>} />;
const IconDot = (p) => <Icon {...p} d={<><circle cx="12" cy="12" r="4" fill="currentColor"/></>} />;
const IconCheck = (p) => <Icon {...p} d={<><path d="M5 12l5 5 9-11"/></>} />;
const IconClock = (p) => <Icon {...p} d={<><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>} />;
const IconUsers = (p) => <Icon {...p} d={<><circle cx="9" cy="9" r="3"/><path d="M3 19c0-3 3-5 6-5s6 2 6 5"/><circle cx="17" cy="8" r="2.4"/><path d="M15 14c3 0 6 2 6 5"/></>} />;
const IconDatabase = (p) => <Icon {...p} d={<><ellipse cx="12" cy="5" rx="8" ry="2.5"/><path d="M4 5v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5V5"/><path d="M4 11v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5v-6"/></>} />;
const IconClipboard = (p) => <Icon {...p} d={<><rect x="6" y="4" width="12" height="17" rx="1.5"/><path d="M9 4h6v3H9z"/></>} />;
const IconLayers = (p) => <Icon {...p} d={<><path d="M12 3l9 5-9 5-9-5 9-5z"/><path d="M3 13l9 5 9-5"/></>} />;
const IconBriefcase = (p) => <Icon {...p} d={<><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/></>} />;
const IconSettings  = (p) => <Icon {...p} d={<><circle cx="12" cy="12" r="3"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></>} />;
const IconChevronLeft  = (p) => <Icon {...p} d={<><path d="M15 6l-6 6 6 6"/></>} />;
const IconChevronRight = (p) => <Icon {...p} d={<><path d="M9 6l6 6-6 6"/></>} />;
const IconNetwork = (p) => <Icon {...p} d={<>
  <circle cx="5" cy="12" r="2.5"/><circle cx="19" cy="6" r="2.5"/><circle cx="19" cy="18" r="2.5"/>
  <path d="M7 11.5l10-4.5M7 12.5l10 4.5M19 8.5v7"/>
</>} />;
const IconHome = (p) => <Icon {...p} d={<><path d="M4 11l8-7 8 7"/><path d="M6 10v9h12v-9"/></>} />;
const IconEye = (p) => <Icon {...p} d={<><path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></>} />;
const IconPlus = (p) => <Icon {...p} d={<><path d="M12 5v14M5 12h14"/></>} />;
const IconTrash = (p) => <Icon {...p} d={<><path d="M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"/></>} />;
const IconKey = (p) => <Icon {...p} d={<><circle cx="8" cy="14" r="4"/><path d="M11 11l9-9M17 4l3 3M15 6l3 3"/></>} />;
const IconMail = (p) => <Icon {...p} d={<><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></>} />;
const IconAlert = (p) => <Icon {...p} d={<><circle cx="12" cy="12" r="9"/><path d="M12 8v5M12 16h.01"/></>} />;
const IconFile = (p) => <Icon {...p} d={<><path d="M6 2h7l5 5v15H6z"/><path d="M13 2v5h5"/></>} />;
const IconSend = (p) => <Icon {...p} d={<><path d="M22 2L11 13M22 2l-7 20-4-9-9-4z"/></>} />;
const IconRocket = (p) => <Icon {...p} d={<><path d="M5 15c-1.5 1-2 4-2 4s3-.5 4-2"/><path d="M9 13l-2-2c1-4 4-8 9-9 1 5-3 8-7 9z"/><circle cx="14" cy="8" r="1.3"/></>} />;

Object.assign(window, {
  IconSparkles, IconTable, IconMatrix, IconRoadmap,
  IconArrowRight, IconArrowUpRight, IconChevronDown, IconChevronUp, IconChevronLeft, IconChevronRight,
  IconX, IconSearch, IconDownload, IconShare, IconDot, IconCheck,
  IconClock, IconUsers, IconDatabase, IconClipboard, IconLayers, IconBriefcase, IconSettings,
  IconNetwork, IconHome, IconEye, IconPlus, IconTrash, IconKey, IconMail, IconAlert, IconFile, IconSend, IconRocket,
});

// ---------------------------------------------------------------------------
// The Linea wordmark + brand dot. Single source of truth — used in the report
// shell, the login screen, and the admin console. The dot is sized and nudged
// relative to `size` so it stays optically centred on the word at any scale;
// pass `color` for dark backgrounds (the dot is always brand blue).
function LineaLogo({ size = 14, color = 'var(--ink-1)', weight = 600 }) {
  return (
    <span aria-label="Linea" style={{display:'inline-flex', alignItems:'center', lineHeight:1, fontFamily:"'Outfit', sans-serif", letterSpacing:'-0.02em', fontWeight:weight, fontSize:size, color}}>
      Linea<span aria-hidden="true" style={{display:'block', width:4, height:4, borderRadius:'50%', background:'var(--blue)', marginLeft:2, marginTop:2, flexShrink:0}}></span>
    </span>
  );
}
const LineaMark = LineaLogo; // back-compat alias

function ClientMark({ size = 18 }) {
  return (
    <div style={{fontFamily:'"DM Serif Display", serif', fontSize: size, lineHeight:1, letterSpacing:'-0.01em', color:'var(--ink-0)'}}>
      {window.CLIENT.name}
    </div>
  );
}

// ---------------------------------------------------------------------------
function Sidebar({ active, onNav, collapsed, onToggle, sections }) {
  const sec = Object.assign({ summary: true, data: true, workflows: true, roadmap: true }, sections || {});
  const allItems = [
    { key: 'summary',   label: 'Executive Summary',  Icon: IconSparkles },
    { key: 'data',      label: 'Data Readiness',      Icon: IconDatabase },
    { key: 'workflows', label: 'Workflow Inventory',  Icon: IconLayers },
    { key: 'roadmap',   label: 'Execution Roadmap',   Icon: IconRoadmap },
  ];
  const items = allItems.filter(item => sec[item.key] !== false);
  if (window.__isAdminSession) {
    items.push({ key: 'admin', label: 'Admin Panel', Icon: IconSettings });
  }
  return (
    <aside className={"sidebar" + (collapsed ? ' sidebar--collapsed' : '')}>
      <div className="sidebar-top">
        {!collapsed && (
          <div className="sidebar-client">
            <div className="kicker">Readiness Assessment</div>
            <ClientMark size={17} />
          </div>
        )}
        <button
          className="sidebar-toggle"
          onClick={onToggle}
          title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
        >
          {collapsed ? <IconChevronRight size={14}/> : <IconChevronLeft size={14}/>}
        </button>
      </div>
      <nav className="sidebar-nav">
        {items.map(({key, label, Icon: I}) => (
          <button
            key={key}
            className={"nav-item" + (active === key ? ' is-active' : '')}
            onClick={() => onNav(key)}
            title={collapsed ? label : ''}
          >
            <I size={15} />
            {!collapsed && <span>{label}</span>}
          </button>
        ))}
      </nav>
      {!collapsed && (
        <div className="sidebar-foot">
          <div className="foot-row">
            <span className="foot-k">Delivered</span>
            <span className="foot-v">{window.CLIENT.deliveredOn}</span>
          </div>
          <div className="foot-row">
            <span className="foot-k">Lead</span>
            <span className="foot-v">{window.CLIENT.engagementLead}</span>
          </div>
          <div className="foot-row foot-row--linea">
            <span className="foot-k">Prepared by</span>
            <LineaMark size={12} />
          </div>
          {window.logout && (
            <div className="foot-row" style={{paddingTop:8, marginTop:4, borderTop:'1px solid var(--rule)'}}>
              <button className="logout-btn" onClick={window.logout}>Log out</button>
            </div>
          )}
        </div>
      )}
    </aside>
  );
}

function Topbar({ active }) {
  const [shareOpen, setShareOpen] = useState(false);
  const [shareEmail, setShareEmail] = useState('');
  const [shareSent, setShareSent] = useState(false);

  const handleShare = () => {
    if (!shareEmail.trim()) return;
    const url = window.location.href;
    const subject = encodeURIComponent(window.CLIENT.name + ' — AI Readiness Assessment');
    const body = encodeURIComponent('I\'d like to share this AI Readiness Assessment with you:\n\n' + url);
    window.open('mailto:' + shareEmail + '?subject=' + subject + '&body=' + body);
    setShareSent(true);
    setTimeout(() => { setShareOpen(false); setShareSent(false); setShareEmail(''); }, 1800);
  };

  const closeShare = () => { setShareOpen(false); setShareEmail(''); setShareSent(false); };

  return (
    <>
      <header className="topbar">
        <div className="topbar-left">
          {window.CLIENT.logo
            ? <img src={window.CLIENT.logo} alt={window.CLIENT.name} className="topbar-logo" />
            : <div className="topbar-client">{window.CLIENT.name}</div>
          }
          <span className="topbar-dot">·</span>
          <div className="topbar-title">AI Readiness Assessment</div>
        </div>
        <div className="topbar-right">
          <div className="topbar-meta">
            <span>Delivered by</span>
            <LineaMark size={12} />
            <span className="dot-sep">·</span>
            <span>{window.CLIENT.deliveredOn}</span>
          </div>
          <button className="ghost-btn" onClick={() => setShareOpen(true)}><IconShare size={14}/>Share</button>
          <button className="ghost-btn" onClick={() => window.print()}><IconDownload size={14}/>Export</button>
        </div>
      </header>
      {shareOpen && (
        <div className="modal-backdrop" onClick={closeShare}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal-head">
              <h3 className="modal-title">Share this report</h3>
              <button className="icon-btn" onClick={closeShare}><IconX size={16}/></button>
            </div>
            <p className="modal-desc">Opens your email client with a pre-filled message and a link to this assessment.</p>
            <div className="modal-field">
              <label className="modal-label">Recipient email</label>
              <input
                className="modal-input"
                type="email"
                placeholder="colleague@example.com"
                value={shareEmail}
                onChange={e => setShareEmail(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && handleShare()}
                autoFocus
              />
            </div>
            <div className="modal-actions">
              <button className="btn-ghost" onClick={closeShare}>Cancel</button>
              <button className="btn-primary" onClick={handleShare} disabled={!shareEmail.trim()}>
                {shareSent ? <><IconCheck size={14}/>Opened in mail</> : <>Send via email <IconArrowUpRight size={14}/></>}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

// ---------------------------------------------------------------------------
// Status pill + classification chip
function TierPill({ tier }) {
  const map = {
    'Ready Now':    { c: 'good',    dot: '#19a463' },
    'Needs Prep':   { c: 'warn',    dot: '#b07a18' },
    'Longer-Term':  { c: 'muted',   dot: '#7a7d85' },
  };
  const s = map[tier] || map['Longer-Term'];
  return (
    <span className={"pill pill--" + s.c}>
      <span className="pill-dot" style={{background:s.dot}}></span>
      {tier}
    </span>
  );
}

function StatusChip({ status }) {
  const map = {
    'Fully manual':         { c: 'muted' },
    'Partially automated':  { c: 'warn' },
    'Already handled':      { c: 'good' },
  };
  const s = map[status] || { c: 'muted' };
  return <span className={"chip chip--" + s.c}>{status}</span>;
}

function PriorityTag({ p }) {
  const label = { P0: 'Phase 1', P1: 'Phase 2', P2: 'Phase 3' }[p] || p;
  return <span className={"prio prio--" + p.toLowerCase()}>{label}</span>;
}

Object.assign(window, {
  Sidebar, Topbar, TierPill, StatusChip, PriorityTag, ClientMark, LineaMark, LineaLogo,
});
