// OrgLens — Agentforce Readiness

function AIReadiness({ readiness, findings, onOpenFinding, onNavigate }) {
  const aiStyles = {
    page: { flex: 1, overflow: 'auto', background: '#f3f2f2', padding: 16 },
    header: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 16, gap: 16 },
    eyebrow: { fontSize: 11, fontWeight: 700, color: '#706e6b', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 },
    title: { fontSize: 22, fontWeight: 700, color: '#080707', letterSpacing: '-0.01em' },
    sub: { fontSize: 13, color: '#3e3e3c', marginTop: 4 },
    grid: { display: 'grid', gridTemplateColumns: '380px 1fr', gap: 16 },
  };
  const aiFindings = findings.filter(f => f.category === 'ai' && f.status === 'open');

  return (
    <div style={aiStyles.page}>
      <div style={aiStyles.header}>
        <div>
          <div style={aiStyles.eyebrow}>Agentforce Readiness</div>
          <div style={aiStyles.title}>Is your org clean enough to trust with agents?</div>
          <div style={aiStyles.sub}>
            Most AI rollouts fail because of metadata, not models. We score the things agents actually consume.
          </div>
        </div>
        <Btn variant="brand" icon={ICONS.download}>Download readiness report</Btn>
      </div>

      <div style={aiStyles.grid}>
        <AIScoreCard score={readiness.overall}/>
        <AIWhatToFix readiness={readiness} onNavigate={onNavigate}/>
      </div>

      <div style={{marginTop: 16}}>
        <AIObjectBreakdown drivers={readiness.drivers}/>
      </div>

      <div style={{marginTop: 16}}>
        <AIFindingsStrip findings={aiFindings} onOpenFinding={onOpenFinding}/>
      </div>
    </div>
  );
}

function AIScoreCard({ score }) {
  const band = scoreBand(score);
  return (
    <Card style={{padding: 0}}>
      <div style={{
        padding: 20, background: 'linear-gradient(135deg, #032d60 0%, #0a4a8c 100%)',
        color: '#fff', borderRadius: '4px 4px 0 0',
      }}>
        <div style={{
          fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,0.7)',
          textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6,
        }}>
          <Icon d={ICONS.sparkle} size={11} style={{display:'inline-block', verticalAlign:'-1px', marginRight: 4}}/>
          Agentforce Readiness Score
        </div>
        <div style={{display: 'flex', alignItems: 'center', gap: 20}}>
          <div style={{position: 'relative'}}>
            <svg width="120" height="120" style={{transform: 'rotate(-90deg)'}}>
              <circle cx="60" cy="60" r="52" fill="none" stroke="rgba(255,255,255,0.15)" strokeWidth="10"/>
              <circle cx="60" cy="60" r="52" fill="none" stroke="#fcb95b" strokeWidth="10"
                strokeDasharray={2 * Math.PI * 52}
                strokeDashoffset={2 * Math.PI * 52 * (1 - score/100)}
                strokeLinecap="round"/>
            </svg>
            <div style={{
              position: 'absolute', inset: 0,
              display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{fontSize: 36, fontWeight: 700, lineHeight: 1, letterSpacing: '-0.02em'}}>{score}</div>
              <div style={{fontSize: 10, opacity: 0.7, marginTop: 2, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em'}}>/ 100</div>
            </div>
          </div>
          <div>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '4px 10px', borderRadius: 4,
              background: 'rgba(252, 185, 91, 0.2)', color: '#fcb95b',
              fontSize: 12, fontWeight: 700, marginBottom: 8,
            }}>
              <Icon d={ICONS.warn} size={12}/>{band.label}
            </div>
            <div style={{fontSize: 13, lineHeight: 1.5, color: 'rgba(255,255,255,0.9)'}}>
              Your org is <b>not ready</b> to deploy customer-facing agents on Account or Opportunity.
            </div>
          </div>
        </div>
      </div>
      <div style={{padding: 16, display: 'flex', flexDirection: 'column', gap: 10}}>
        <div style={{fontSize: 11, fontWeight: 700, color: '#706e6b', textTransform: 'uppercase', letterSpacing: '0.06em'}}>
          What we measure
        </div>
        {[
          ['Field documentation coverage',  '58%', 'High gap'],
          ['Picklist value consistency',    '64%', 'Medium gap'],
          ['Duplicate / overlapping fields', '11 found', 'High gap'],
          ['Sensitive data exposure surface', '4 profiles', 'High gap'],
          ['Stale or untrusted records',     '31% on Case', 'Medium gap'],
          ['Conflicting status fields',      '4 on Opp.',  'High gap'],
        ].map(([label, val, sev]) => (
          <div key={label} style={{display:'flex', alignItems:'center', gap: 8, fontSize: 12}}>
            <span style={{
              width: 6, height: 6, borderRadius: '50%',
              background: sev === 'High gap' ? '#c23934' : '#dd7a01', flexShrink: 0,
            }}/>
            <span style={{flex: 1, color: '#3e3e3c'}}>{label}</span>
            <span style={{fontWeight: 700, color: '#080707'}}>{val}</span>
          </div>
        ))}
      </div>
    </Card>
  );
}

function AIWhatToFix({ readiness, onNavigate }) {
  return (
    <Card style={{padding: 0, display: 'flex', flexDirection: 'column'}}>
      <CardHeader
        eyebrow="The Agentforce wedge"
        title="Clean these objects first — then deploy agents"
        icon={ICONS.sparkle}
      />
      <div style={{padding: 20, display: 'flex', flexDirection: 'column', gap: 16}}>
        <div style={{
          padding: 14, background: '#eaf4ff', border: '1px solid #1b96ff',
          borderRadius: 4, fontSize: 13, lineHeight: 1.6, color: '#032d60',
        }}>
          <b>The problem:</b> agents reason over the same metadata humans do. If a field has no description, conflicting picklist values, or duplicate siblings — the agent will produce confident, wrong answers about your customers.
        </div>

        {/* Object readiness mini bars */}
        <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
          {readiness.drivers.map(d => {
            const c = scoreColor(d.score);
            return (
              <div key={d.object}>
                <div style={{display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6}}>
                  <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
                    <span style={{
                      width: 22, height: 22, borderRadius: 4,
                      background: window.CATEGORY_META.ai.color,
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
                    }}><Icon d={ICONS.field} size={11}/></span>
                    <span style={{fontSize: 14, fontWeight: 700, color: '#080707'}}>{d.object}</span>
                    <span style={{
                      fontSize: 10, color: c, fontWeight: 700, padding: '1px 6px',
                      background: c === '#2e844a' ? '#f3fbf2' : c === '#dd7a01' ? '#fffaef' : '#fce7e7',
                      borderRadius: 4, textTransform: 'uppercase', letterSpacing: '0.04em',
                    }}>{d.issues.length} blockers</span>
                  </div>
                  <span style={{fontSize: 16, fontWeight: 700, color: c, letterSpacing: '-0.01em'}}>{d.score}/100</span>
                </div>
                <HBar value={d.score} color={c} height={6}/>
                <div style={{fontSize: 11, color: '#706e6b', marginTop: 6, lineHeight: 1.5}}>
                  {d.issues.map((iss, idx) => (
                    <span key={idx}>
                      <b style={{color: iss.severity === 'critical' ? '#8e0c0c' : iss.severity === 'high' ? '#ba0517' : '#a96404'}}>{iss.value}</b>
                      <span style={{color: '#3e3e3c'}}> {iss.label}</span>
                      {idx < d.issues.length - 1 && <span style={{margin: '0 6px', color: '#dddbda'}}>·</span>}
                    </span>
                  ))}
                </div>
              </div>
            );
          })}
        </div>

        <div style={{
          marginTop: 8, padding: 12, background: '#fafaf9',
          border: '1px solid #ecebea', borderRadius: 4,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{flex: 1, fontSize: 12, color: '#3e3e3c', lineHeight: 1.5}}>
            Estimated cleanup time before customer-facing agents are safe: <b>3–5 days of admin work</b>.
          </div>
          <Btn variant="brand" size="sm" onClick={() => onNavigate('backlog')}>Open AI backlog</Btn>
        </div>
      </div>
    </Card>
  );
}

function AIObjectBreakdown({ drivers }) {
  // Comparative grid showing field doc coverage, picklist consistency, etc.
  return (
    <Card style={{padding: 0}}>
      <CardHeader eyebrow="Per-object readiness signals" title="Where the gaps hide" icon={ICONS.report}/>
      <div style={{overflowX: 'auto'}}>
        <table style={{width: '100%', borderCollapse: 'collapse'}}>
          <thead>
            <tr style={{background: '#fafaf9'}}>
              {['Object', 'Field doc coverage', 'Picklist consistency', 'Duplicate fields', 'Profile exposure', 'Data freshness', 'Action'].map(h => (
                <th key={h} style={{
                  padding: '10px 12px', fontSize: 11, fontWeight: 700, color: '#706e6b',
                  textTransform: 'uppercase', letterSpacing: '0.05em', textAlign: 'left',
                  borderBottom: '1px solid #dddbda', whiteSpace: 'nowrap',
                }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {[
              { obj: 'Account',     doc: 58, picklist: 71, dup: 11, exp: 'High',   fresh: 82, color: window.CATEGORY_META.data.color },
              { obj: 'Opportunity', doc: 64, picklist: 42, dup:  7, exp: 'Medium', fresh: 88, color: window.CATEGORY_META.ai.color },
              { obj: 'Contact',     doc: 42, picklist: 78, dup:  3, exp: 'Critical', fresh: 69, color: window.CATEGORY_META.security.color },
              { obj: 'Case',        doc: 51, picklist: 66, dup:  2, exp: 'Low',    fresh: 31, color: window.CATEGORY_META.automation.color },
              { obj: 'Lead',        doc: 72, picklist: 83, dup:  1, exp: 'Low',    fresh: 91, color: window.CATEGORY_META.release.color },
            ].map((r, i) => (
              <tr key={r.obj}>
                <td style={{padding: '12px', borderBottom: '1px solid #ecebea', fontWeight: 700}}>
                  <div style={{display:'flex', alignItems:'center', gap: 8}}>
                    <span style={{width: 22, height: 22, borderRadius: 4, background: r.color, color:'#fff', display:'inline-flex', alignItems:'center', justifyContent:'center'}}>
                      <Icon d={ICONS.field} size={11}/>
                    </span>
                    {r.obj}
                  </div>
                </td>
                <PercentCell value={r.doc}/>
                <PercentCell value={r.picklist}/>
                <td style={{padding: '12px', borderBottom: '1px solid #ecebea', fontSize: 13}}>
                  <span style={{fontWeight: 700, color: r.dup > 5 ? '#ba0517' : r.dup > 2 ? '#a96404' : '#3e3e3c'}}>{r.dup}</span>
                  <span style={{fontSize: 11, color: '#706e6b', marginLeft: 4}}>fields</span>
                </td>
                <td style={{padding: '12px', borderBottom: '1px solid #ecebea'}}>
                  <ImpactTagInline impact={r.exp}/>
                </td>
                <PercentCell value={r.fresh}/>
                <td style={{padding: '12px', borderBottom: '1px solid #ecebea'}}>
                  <Btn variant="text" size="sm">Inspect <Icon d={ICONS.chevR} size={10}/></Btn>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

function PercentCell({ value }) {
  const color = scoreColor(value);
  return (
    <td style={{padding: '12px', borderBottom: '1px solid #ecebea', minWidth: 130}}>
      <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
        <div style={{width: 60}}><HBar value={value} color={color} height={5}/></div>
        <span style={{fontSize: 12, fontWeight: 700, color: '#080707'}}>{value}%</span>
      </div>
    </td>
  );
}

function ImpactTagInline({ impact }) {
  const map = {
    Critical: { color: '#8e0c0c', bg: '#fce7e7' },
    High:     { color: '#ba0517', bg: '#fce7e7' },
    Medium:   { color: '#a96404', bg: '#fffaef' },
    Low:      { color: '#3e3e3c', bg: '#f3f2f2' },
  };
  const m = map[impact] || map.Low;
  return (
    <span style={{
      display: 'inline-block', padding: '2px 8px', borderRadius: 4,
      background: m.bg, color: m.color, fontSize: 11, fontWeight: 700,
    }}>{impact}</span>
  );
}

function AIFindingsStrip({ findings, onOpenFinding }) {
  return (
    <Card style={{padding: 0}}>
      <CardHeader eyebrow="AI-related findings" title="Open these to plan your agent prep sprint" icon={ICONS.sparkle}/>
      <div>
        {findings.map((f, i) => (
          <div key={f.id} onClick={() => onOpenFinding(f)} style={{
            padding: '14px 16px',
            borderBottom: i < findings.length - 1 ? '1px solid #ecebea' : 'none',
            display: 'flex', alignItems: 'center', gap: 12,
            cursor: 'pointer', transition: 'background 150ms',
          }} onMouseEnter={e => e.currentTarget.style.background = '#fafaf9'}
             onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <PriorityPill priority={f.priority}/>
            <div style={{flex: 1, minWidth: 0}}>
              <div style={{fontSize: 13, fontWeight: 700, color: '#080707'}}>{f.title}</div>
              <div style={{fontSize: 11, color: '#706e6b', marginTop: 2}}>{f.object} · Risk {f.riskScore} · {f.effort} effort</div>
            </div>
            <Icon d={ICONS.chevR} size={14} color="#706e6b"/>
          </div>
        ))}
        {findings.length === 0 && (
          <div style={{padding: 32, textAlign: 'center', color: '#706e6b', fontSize: 13}}>
            All AI-readiness findings have been addressed. Nice.
          </div>
        )}
      </div>
    </Card>
  );
}

Object.assign(window, { AIReadiness });
