// Institutional CRM — shared shell pieces (icons, chrome, small primitives)
const IC = ({ d, size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" dangerouslySetInnerHTML={{ __html: d }} />
);
const ICONS = {
  home: '<path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/>',
  funnel: '<path d="M3 4h18l-7 8v6l-4 2v-8L3 4z"/>',
  deals: '<path d="M3 5h18M3 10h13M3 15h9M3 20h6"/>',
  clients: '<circle cx="9" cy="8" r="3.4"/><path d="M2.5 20c0-3.6 2.9-6 6.5-6s6.5 2.4 6.5 6"/><path d="M16 5.2a3.4 3.4 0 0 1 0 5.7"/><path d="M18.5 14.5c1.9.9 3 2.6 3 5.5"/>',
  calc: '<rect x="5" y="2.5" width="14" height="19" rx="2"/><path d="M9 7h6"/><path d="M9 12h.01M12 12h.01M15 12h.01M9 16h.01M12 16h.01M15 16h.01"/>',
  synd: '<circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 9 9h-9z"/>',
  comm: '<path d="M12 2v20"/><path d="M17 6H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>',
  chart: '<path d="M4 20V10M10 20V4M16 20v-8M22 20H2"/>',
  partners: '<path d="M8 12.5 10.5 15c.9.9 2.3.9 3.2 0l4.8-4.8a2.3 2.3 0 0 0 0-3.2l-2.6-2.6a2.3 2.3 0 0 0-3.2 0L11.5 5.6"/><path d="M12.5 11.5 10 9c-.9-.9-2.3-.9-3.2 0L4.6 11.2a2.3 2.3 0 0 0 0 3.2l4.4 4.4c.9.9 2.3.9 3.2 0l1.3-1.3"/>',
  search: '<circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/>',
  bell: '<path d="M18 8a6 6 0 1 0-12 0c0 7-3 8-3 8h18s-3-1-3-8"/><path d="M10.3 21a2 2 0 0 0 3.4 0"/>',
  user: '<circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 3.6-6.5 8-6.5s8 2.5 8 6.5"/>',
  more: '<path d="M4 7h16M4 12h16M4 17h16"/>',
  zap: '<path d="M13 2 4 14h6l-1 8 9-12h-6l1-8z"/>',
  bulb: '<path d="M9 18h6M10 21h4"/><path d="M12 3a6 6 0 0 0-3.5 10.9c.8.6 1.5 1.9 1.5 2.6h4c0-.7.7-2 1.5-2.6A6 6 0 0 0 12 3z"/>',
  check: '<path d="M20 6 9 17l-5-5"/>',
  print: '<path d="M6 9V3h12v6"/><rect x="3" y="9" width="18" height="8" rx="1.5"/><path d="M6 14h12v7H6z"/>',
};

// Brand wordmarks (type-only for ExpressFund; debtlift has the JPG asset)
const EFWordmark = ({ light, size = 19 }) => (
  <span style={{ fontSize: size, fontWeight: 800, letterSpacing: '.3px', lineHeight: 1 }}>
    <span style={{ color: light ? '#fff' : 'var(--inst-navy)' }}>EXPRESS</span>
    <span style={{ color: light ? '#9fc0f2' : 'var(--brand-300)' }}>FUND</span>
  </span>
);

function Chip({ tone = '', children }) {
  return <span className={`inst-chip ${tone}`}><span className="dot"></span>{children}</span>;
}

// Company tag — makes it obvious which brand a record belongs to
function BrandTag({ brand }) {
  if (!brand) return null;
  const ef = brand === 'ExpressFund';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', fontSize: 10, fontWeight: 800,
      letterSpacing: '.5px', textTransform: 'uppercase', padding: '2px 8px', borderRadius: 3,
      whiteSpace: 'nowrap', lineHeight: '14px',
      background: ef ? 'var(--inst-navy)' : '#EEF3FD',
      color: ef ? '#fff' : '#2356CC',
      border: '1px solid ' + (ef ? 'var(--inst-navy)' : '#7AAEE8'),
    }}>{ef ? 'ExpressFund' : 'debtlift'}</span>
  );
}
const STAGE_TONE = { 'New': 'blue', 'Contacted': '', 'Qualified': 'blue', 'Offer Sent': 'amber', 'Application': 'amber', 'Underwriting': 'navy', 'Funded': 'green', 'Lost': 'red', 'Contracts Sent': 'amber', 'Signed': 'navy', 'Active': 'green' };
const SERV_TONE = { 'Performing': 'green', 'Modified Payment': 'amber', 'In Settlement': 'red' };

// Renewal eligibility — alerts as a file crosses 25 / 50 / 100% completed
const RENEWAL_TIERS = [100, 50, 25];
const RENEWAL_TONE = { 25: 'blue', 50: 'amber', 100: 'green' };
function renewalTier(pct) { if (pct == null) return null; for (let i = 0; i < RENEWAL_TIERS.length; i++) { if (pct >= RENEWAL_TIERS[i]) return RENEWAL_TIERS[i]; } return null; }
function RenewalChip({ pct }) {
  const t = renewalTier(pct);
  if (t == null) return null;
  return <Chip tone={RENEWAL_TONE[t]}>{'Renewal · ' + t + '%'}</Chip>;
}

function SectionCard({ bar, right, children, style }) {
  return (
    <div className="inst-card" style={style}>
      <div className="inst-section-bar"><span>{bar}</span>{right ? <span className="right">{right}</span> : null}</div>
      {children}
    </div>
  );
}

// Full-page file view shell — breadcrumb, back link, header, right-aligned stats
function FilePage({ crumb, backLabel, onBack, title, sub, chips, stats, children }) {
  return (
    <div className="inst-page">
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.6px', textTransform: 'uppercase', color: 'var(--inst-ink-3)', marginBottom: 8 }}>{crumb}</div>
      <a className="inst-link" onClick={onBack} style={{ display: 'inline-block', marginBottom: 14 }}>‹ {backLabel}</a>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18, flexWrap: 'wrap', marginBottom: 18 }}>
        <div style={{ flex: 1, minWidth: 240 }}>
          <div className="inst-greeting" style={{ margin: 0 }}>{title}</div>
          <div style={{ fontSize: 13, color: 'var(--inst-ink-3)', marginTop: 4 }}>{sub}</div>
          <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap', alignItems: 'center' }}>{chips}</div>
        </div>
        {stats}
      </div>
      {children}
    </div>
  );
}

function Modal({ title, onClose, children, footer, width = 560 }) {
  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(22,40,63,.55)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{ background: '#fff', borderRadius: 8, width: '100%', maxWidth: width, maxHeight: '92vh', overflowY: 'auto' }}>
        <div className="inst-section-bar" style={{ borderRadius: '8px 8px 0 0' }}>
          <span>{title}</span>
          <button onClick={onClose} style={{ background: 'none', border: 'none', color: '#fff', fontSize: 20, cursor: 'pointer', lineHeight: 1, padding: 0 }}>×</button>
        </div>
        <div style={{ padding: 20 }}>{children}</div>
        {footer ? <div style={{ padding: '0 20px 20px', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>{footer}</div> : null}
      </div>
    </div>
  );
}

function Field({ label, children, full }) {
  return <div className="inst-field" style={{ gridColumn: full ? '1/-1' : undefined }}><label>{label}</label>{children}</div>;
}

function Toast({ msg }) {
  if (!msg) return null;
  return (
    <div style={{ position: 'fixed', bottom: 84, left: '50%', transform: 'translateX(-50%)', background: 'var(--inst-navy)', color: '#fff', fontSize: 13, fontWeight: 600, padding: '10px 18px', borderRadius: 6, zIndex: 300, boxShadow: '0 6px 20px rgba(12,44,94,.35)', display: 'flex', gap: 8, alignItems: 'center' }}>
      <IC d={ICONS.check} size={15} /> {msg}
    </div>
  );
}

function useToastI() {
  const [msg, setMsg] = React.useState(null);
  const toast = m => { setMsg(m); setTimeout(() => setMsg(null), 2200); };
  return { msg, toast };
}

// Simple funnel bar (stage counts)
function FunnelBar({ leads, onStage, stages }) {
  const FN = stages || window.ICRM.FUNNEL;
  return (
    <div className="inst-funnel">
      {FN.map((st, i) => {
        const n = leads.filter(l => l.stage === st).length;
        return (
          <button key={st} onClick={() => onStage && onStage(st)} style={{
            background: n ? 'var(--inst-navy)' : '#fff',
            color: n ? '#fff' : 'var(--inst-ink-3)', border: '1px solid ' + (n ? 'var(--inst-navy)' : 'var(--inst-rule)'),
            opacity: n ? (0.55 + 0.45 * ((i + 1) / FN.length)) : 1,
            padding: '10px 8px', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'center',
            borderRadius: 4,
          }}>
            <div style={{ fontSize: 20, fontWeight: 800, lineHeight: 1 }}>{n}</div>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.4px', textTransform: 'uppercase', marginTop: 4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{st}</div>
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, { IC, ICONS, EFWordmark, Chip, BrandTag, STAGE_TONE, SERV_TONE, SectionCard, FilePage, Modal, Field, Toast, useToastI, FunnelBar, renewalTier, RenewalChip });
