/* ============================================================
 * Shared primitives — icons, badges, stat cards, field rows,
 * section headers. Used by both portals.
 * ============================================================ */

/* --- Heroicons outline path data (1.5 px stroke style) -------- */
window.Icons = {
  dashboard:  <><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></>,
  projects:   <><path d="M3 7l9-4 9 4M3 7v10l9 4 9-4V7M3 7l9 4 9-4"/></>,
  document:   <><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6"/></>,
  check:      <><polyline points="20 6 9 17 4 12"/></>,
  clock:      <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>,
  shield:     <><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></>,
  link:       <><path d="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757"/><path d="M10.81 15.312a4.5 4.5 0 01-1.242-7.244l4.5-4.5a4.5 4.5 0 016.364 6.364l-1.757 1.757"/></>,
  globe:      <><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/></>,
  pin:        <><path d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/><path d="M19 11c0 7-7 11-7 11s-7-4-7-11a7 7 0 1114 0z"/></>,
  search:     <><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></>,
  bell:       <><path d="M18 16v-5a6 6 0 10-12 0v5l-2 2v1h16v-1l-2-2zM10 21a2 2 0 004 0"/></>,
  chevronDown:<><polyline points="6 9 12 15 18 9"/></>,
  arrowRight: <><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></>,
  upload:     <><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12"/></>,
  filter:     <><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></>,
  plus:       <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
  hedera:     <><circle cx="12" cy="12" r="9"/><path d="M8 8v8M16 8v8M8 12h8"/></>,
  alert:      <><path d="M12 9v4M12 17h.01"/><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/></>,
  flag:       <><line x1="4" y1="22" x2="4" y2="15"/><path d="M4 15V2h13l-2 4 2 4H4"/></>,
  signature:  <><path d="M20 19h-9.5a2.5 2.5 0 010-5h7a2.5 2.5 0 000-5H4"/><path d="M4 9V5"/></>,
  eye:        <><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></>,
  user:       <><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></>,
  back:       <><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></>,
  download:   <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></>,
  edit:       <><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></>,
  lock:       <><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></>,
  external:   <><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></>,
  branch:     <><circle cx="6" cy="6" r="3"/><circle cx="18" cy="18" r="3"/><path d="M6 9v6a6 6 0 0 0 6 6h0"/></>,
  reply:      <><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></>,
  trash:      <><polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/></>,
  building:   <><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 9h.01M15 9h.01M9 13h.01M15 13h.01M9 17h.01M15 17h.01"/></>,
  star:       <><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></>,
  layers:     <><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></>,
  list:       <><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></>,
  map:        <><polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/><line x1="8" y1="2" x2="8" y2="18"/><line x1="16" y1="6" x2="16" y2="22"/></>,
};

function PamojaIcon({ name, size = 18, color = 'currentColor', stroke = 1.6, style = {} }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
         stroke={color} strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={style}>
      {Icons[name]}
    </svg>
  );
}

/* --- IconTile ----------------------------------------------- */
function IconTile({ children, color = '#F4C300', size = 44 }) {
  const inner = Math.round(size * 0.5);
  return (
    <div style={{
      width: size, height: size, borderRadius: 10,
      background: hexToRgba(color, 0.10),
      display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
    }}>
      <svg width={inner} height={inner} viewBox="0 0 24 24" fill="none"
           stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        {children}
      </svg>
    </div>
  );
}
function hexToRgba(hex, a){
  const h = hex.replace('#','');
  const r = parseInt(h.slice(0,2),16), g = parseInt(h.slice(2,4),16), b = parseInt(h.slice(4,6),16);
  return `rgba(${r},${g},${b},${a})`;
}

/* --- Badge -------------------------------------------------- */
function Badge({ variant = 'gray', children, dot = false, mono = false }) {
  const V = {
    green:  { bg:'#D1FAE5', fg:'#065F46' },
    gold:   { bg:'#FFF8E0', fg:'#92400E' },
    blue:   { bg:'#DBEAFE', fg:'#1E40AF' },
    red:    { bg:'#FEE2E2', fg:'#991B1B' },
    amber:  { bg:'#FEF3C7', fg:'#92400E' },
    gray:   { bg:'#F3F4F6', fg:'#4B5563' },
    purple: { bg:'rgba(124,92,252,0.10)', fg:'#7C5CFC' },
    verra:  { bg:'rgba(0,119,182,0.08)',  fg:'#0077B6' },
    puro:   { bg:'rgba(5,150,105,0.08)',  fg:'#059669' },
  }[variant] || { bg:'#F3F4F6', fg:'#4B5563' };
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:6,
      background:V.bg, color:V.fg,
      fontFamily: mono ? "'JetBrains Mono', monospace" : 'inherit',
      fontSize:11, fontWeight:700, letterSpacing: mono ? '0.04em' : '0.02em',
      padding:'2px 8px', borderRadius:9999,
    }}>
      {dot && <span style={{width:6, height:6, borderRadius:'50%', background:V.fg}}/>}
      {children}
    </span>
  );
}

/* --- StatCard ----------------------------------------------- */
function StatCard({ label, value, sub, accent = '#F4C300', icon }) {
  return (
    <div style={{
      background:'#fff', border:'1px solid #E5E7EB', borderRadius:10,
      padding:20, borderLeft:`4px solid ${accent}`,
      display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:12,
    }}>
      <div style={{flex:1, minWidth:0}}>
        <div style={{fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'#9CA3AF', marginBottom:8}}>{label}</div>
        <div style={{fontSize:28, fontWeight:900, color:'#022C28', letterSpacing:'-0.02em', lineHeight:1}}>{value}</div>
        {sub && <div style={{fontSize:11, color:'#6B7280', marginTop:6}}>{sub}</div>}
      </div>
      {icon && <IconTile color={accent} size={40}>{Icons[icon]}</IconTile>}
    </div>
  );
}

/* --- SectionHeader ------------------------------------------ */
function SectionHeader({ eyebrow, title, tail, eyebrowColor = '#F4C300' }) {
  return (
    <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:14}}>
      <div style={{minWidth:0, flex:1}}>
        {eyebrow && <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.12em', color: eyebrowColor}}>{eyebrow}</div>}
        <div style={{fontSize:16, fontWeight:900, color:'#022C28', marginTop:2, letterSpacing:'-0.01em'}}>{title}</div>
      </div>
      {tail && <div style={{fontSize:11, fontWeight:600, color:'#6B7280', whiteSpace:'nowrap', flexShrink:0}}>{tail}</div>}
    </div>
  );
}

/* --- FieldRow (the seven-state pattern) ---------------------- */
const FIELD_STATE = {
  empty:     { bd:'#E5E7EB', bg:'#fff',                       lbl:'Empty',         lblc:'#9CA3AF', icon:'plus' },
  ai:        { bd:'#0077B6', bg:'#E8F4FC',                    lbl:'AI suggested',  lblc:'#0077B6', icon:'star' },
  confirmed: { bd:'#2BC48A', bg:'#E6FBF3',                    lbl:'Confirmed',     lblc:'#059669', icon:'check' },
  flagged:   { bd:'#D97706', bg:'#FEF3C7',                    lbl:'Flagged',       lblc:'#92400E', icon:'flag' },
  committed: { bd:'#7C5CFC', bg:'rgba(124,92,252,0.08)',      lbl:'Committed',     lblc:'#7C5CFC', icon:'lock' },
  imported:  { bd:'#14B8A6', bg:'#CCFBF1',                    lbl:'Verra imported',lblc:'#0F766E', icon:'download' },
  locked:    { bd:'#9CA3AF', bg:'#F3F4F6',                    lbl:'Locked',        lblc:'#4B5563', icon:'lock' },
};

function FieldRow({ state='empty', label, value, who, onClick, dense = false }) {
  const S = FIELD_STATE[state] || FIELD_STATE.empty;
  return (
    <div onClick={onClick} style={{
      border:`1.5px solid ${S.bd}`, background:S.bg, borderRadius:10,
      padding: dense ? '10px 12px' : '12px 14px',
      cursor: onClick ? 'pointer' : 'default',
      transition:'border-color 200ms, transform 150ms',
    }}
    onMouseEnter={e=>{ if(onClick) e.currentTarget.style.borderColor = '#F4C300'; }}
    onMouseLeave={e=>{ if(onClick) e.currentTarget.style.borderColor = S.bd; }}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:4, gap:10}}>
        <div style={{fontSize:10, fontWeight:800, textTransform:'uppercase', letterSpacing:'0.06em', color:S.lblc, lineHeight:1.3, flex:1, minWidth:0}}>{label}</div>
        <span style={{display:'inline-flex', alignItems:'center', gap:4, fontSize:9, fontWeight:800, color:S.lblc, letterSpacing:'0.04em', textTransform:'uppercase', whiteSpace:'nowrap', flexShrink:0, paddingTop:1}}>
          <PamojaIcon name={S.icon} size={10} color={S.lblc} stroke={2}/>
          {S.lbl}
        </span>
      </div>
      <div style={{fontSize:13, fontWeight:700, color:'#022C28', lineHeight:1.35}}>{value}</div>
      {who && <div style={{fontSize:10, color:'#6B7280', marginTop:4, letterSpacing:'0.02em'}}>{who}</div>}
    </div>
  );
}

/* --- Buttons ------------------------------------------------ */
const btnPrimary = {
  minHeight:44, padding:'10px 18px',
  background:'#F4C300', color:'#022C28', border:'none', borderRadius:10,
  fontSize:13, fontWeight:800, cursor:'pointer', fontFamily:'inherit',
  display:'inline-flex', alignItems:'center', gap:8, transition:'all 200ms',
};
const btnSecondary = {
  minHeight:44, padding:'10px 18px',
  background:'transparent', color:'#022C28', border:'1.5px solid #E5E7EB', borderRadius:10,
  fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit',
  display:'inline-flex', alignItems:'center', gap:8, transition:'all 200ms',
};
const btnDanger = {
  minHeight:44, padding:'10px 18px',
  background:'#fff', color:'#DC2626', border:'1.5px solid #FCA5A5', borderRadius:10,
  fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit',
  display:'inline-flex', alignItems:'center', gap:8, transition:'all 200ms',
};

function Btn({ kind='primary', children, onClick, style, disabled, icon, type='button' }) {
  const base = kind === 'primary' ? btnPrimary : kind === 'danger' ? btnDanger : btnSecondary;
  return (
    <button type={type} onClick={onClick} disabled={disabled} style={{
      ...base,
      ...(disabled ? { opacity: 0.5, cursor:'not-allowed' } : {}),
      ...style,
    }}
      onMouseEnter={e=>{
        if(disabled) return;
        if(kind==='primary') e.currentTarget.style.background = '#D4A800';
        else if(kind==='secondary') e.currentTarget.style.borderColor = '#9CA3AF';
        else if(kind==='danger') { e.currentTarget.style.background = '#FEE2E2'; }
      }}
      onMouseLeave={e=>{
        if(disabled) return;
        if(kind==='primary') e.currentTarget.style.background = '#F4C300';
        else if(kind==='secondary') e.currentTarget.style.borderColor = '#E5E7EB';
        else if(kind==='danger') { e.currentTarget.style.background = '#fff'; }
      }}>
      {icon && <PamojaIcon name={icon} size={14} stroke={2.2}/>}
      {children}
    </button>
  );
}

/* --- Card --------------------------------------------------- */
function Card({ children, style, padding = 24, dark = false, onClick }) {
  return (
    <div onClick={onClick} style={{
      background: dark ? '#022C28' : '#fff',
      color: dark ? '#fff' : 'inherit',
      border: dark ? 'none' : '1px solid #E5E7EB',
      borderRadius:10, padding,
      cursor: onClick ? 'pointer' : 'default',
      transition:'border-color 200ms, box-shadow 200ms',
      ...style,
    }}>
      {children}
    </div>
  );
}

/* --- Empty / Preview state ---------------------------------- */
function PreviewBanner({ children, tone='gold' }) {
  const tones = {
    gold: { bg:'#FFF8E0', bd:'#FDE68A', fg:'#7C5104', dot:'#F4C300' },
    blue: { bg:'#E8F4FC', bd:'#BAE0F7', fg:'#0C4A6E', dot:'#0077B6' },
    gray: { bg:'#F9FAFB', bd:'#E5E7EB', fg:'#4B5563', dot:'#9CA3AF' },
  }[tone];
  return (
    <div style={{
      background: tones.bg, border:`1px solid ${tones.bd}`, borderRadius:10,
      padding:'12px 16px', display:'flex', alignItems:'center', gap:12,
      fontSize:13, color: tones.fg,
    }}>
      <span style={{width:8, height:8, borderRadius:'50%', background:tones.dot, flexShrink:0}}/>
      <div>{children}</div>
    </div>
  );
}

function EmptyState({ icon='document', title, body, action }) {
  return (
    <div style={{
      border:'1.5px dashed #E5E7EB', borderRadius:10, padding:'40px 24px',
      textAlign:'center', background:'#FAFAFA',
    }}>
      <div style={{width:48, height:48, margin:'0 auto 12px', borderRadius:10, background:'#fff', border:'1px solid #E5E7EB', display:'flex', alignItems:'center', justifyContent:'center'}}>
        <PamojaIcon name={icon} size={22} color="#9CA3AF" stroke={1.5}/>
      </div>
      <div style={{fontSize:15, fontWeight:800, color:'#022C28', marginBottom:4}}>{title}</div>
      {body && <div style={{fontSize:13, color:'#6B7280', maxWidth:380, margin:'0 auto', lineHeight:1.5}}>{body}</div>}
      {action && <div style={{marginTop:14}}>{action}</div>}
    </div>
  );
}

/* --- Modal -------------------------------------------------- */
function Modal({ open, onClose, children, width = 640, padding = 0 }) {
  if (!open) return null;
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, background:'rgba(2,44,40,0.55)',
      display:'flex', alignItems:'center', justifyContent:'center', zIndex:100,
      animation:'p-fade 200ms ease-out',
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        background:'#fff', borderRadius:14, padding,
        width:'90%', maxWidth: width, maxHeight:'90vh', overflow:'auto',
        boxShadow:'0 24px 80px rgba(0,0,0,0.25)',
        animation:'p-pop 240ms ease-out',
      }}>
        {children}
      </div>
    </div>
  );
}

window.PamojaIcon = PamojaIcon;
window.IconTile = IconTile;
window.hexToRgba = hexToRgba;
window.Badge = Badge;
window.StatCard = StatCard;
window.SectionHeader = SectionHeader;
window.FieldRow = FieldRow;
window.FIELD_STATE = FIELD_STATE;
window.Btn = Btn;
window.btnPrimary = btnPrimary;
window.btnSecondary = btnSecondary;
window.btnDanger = btnDanger;
window.Card = Card;
window.PreviewBanner = PreviewBanner;
window.EmptyState = EmptyState;
window.Modal = Modal;
