// OrgLens — Dashboard (OrgScore home)

function Dashboard({ overallScore, categories, findings, onNavigate, onOpenFinding, activeOrg, onRescan, onOpenCopilot, showReleaseGuardBanner = true }) {
  const band = scoreBand(overallScore);
  const openFindings = findings.filter(f => f.status === 'open');
  const p1Count = openFindings.filter(f => f.priority === 'P1').length;
  const p2Count = openFindings.filter(f => f.priority === 'P2').length;
  const topFindings = [...openFindings].sort((a,b) => b.riskScore - a.riskScore).slice(0, 5);

  const dashStyles = {
    page: { flex: 1, overflow: 'auto', background: '#f3f2f2', padding: 16 },
    pageHeader: {
      display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
      marginBottom: 16, gap: 16,
    },
    titleWrap: { flex: 1 },
    eyebrow: {
      fontSize: 11, fontWeight: 700, color: '#706e6b',
      textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4,
    },
    title: { fontSize: 22, fontWeight: 700, color: '#080707', letterSpacing: '-0.01em', lineHeight: 1.2 },
    sub: { fontSize: 13, color: '#3e3e3c', marginTop: 4 },
    actions: { display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 },
    grid: { display: 'grid', gridTemplateColumns: '420px 1fr', gap: 16 },
    twoCol: { display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16, marginTop: 16 },
  };

  return (
    <div style={dashStyles.page}>
      <div style={dashStyles.pageHeader}>
        <div style={dashStyles.titleWrap}>
          <div style={dashStyles.eyebrow}>OrgScore · {activeOrg.name}</div>
          <div style={dashStyles.title}>Your org has {openFindings.length} active findings.</div>
          <div style={dashStyles.sub}>
            Last scanned {activeOrg.lastScan} · {activeOrg.edition} edition · {activeOrg.users.toLocaleString()} licensed users
          </div>
        </div>
        <div style={dashStyles.actions}>
          <Btn variant="neutral" size="md" icon={ICONS.download}>Export PDF</Btn>
          <Btn variant="brand" size="md" icon={ICONS.refresh} onClick={onRescan}>Run New Scan</Btn>
        </div>
      </div>

      <div style={dashStyles.grid}>
        <ScoreHero overallScore={overallScore} band={band} categories={categories} p1Count={p1Count} p2Count={p2Count}/>
        <CategoryGrid categories={categories} onNavigate={onNavigate}/>
      </div>

      <div style={dashStyles.twoCol}>
        <TopFindings findings={topFindings} onOpenFinding={onOpenFinding} onNavigate={onNavigate}/>
        <NextActionCard openFindings={openFindings} onNavigate={onNavigate} onOpenCopilot={onOpenCopilot}/>
      </div>

      <ReleaseGuardBanner visible={showReleaseGuardBanner}/>
    </div>
  );
}

// ===== Score Hero =====
function ScoreHero({ overallScore, band, categories, p1Count, p2Count }) {
  const heroStyles = {
    card: {
      background: '#fff', border: '1px solid #dddbda', borderRadius: 4,
      boxShadow: '0 2px 2px 0 rgba(0,0,0,0.05)',
      padding: 24, display: 'flex', flexDirection: 'column', gap: 20,
    },
    top: { display: 'flex', alignItems: 'center', gap: 24 },
    score: { display: 'flex', flexDirection: 'column' },
    big: { fontSize: 64, fontWeight: 700, color: '#080707', lineHeight: 1, letterSpacing: '-0.03em' },
    out: { fontSize: 16, fontWeight: 400, color: '#706e6b', marginLeft: 8 },
    band: (b) => ({
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '4px 10px', borderRadius: 4,
      background: b.bg, color: b.color,
      fontSize: 12, fontWeight: 700, marginTop: 8,
    }),
    note: { fontSize: 13, color: '#3e3e3c', lineHeight: 1.5 },
    stats: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 },
    stat: { borderTop: '1px solid #ecebea', paddingTop: 12 },
    statLbl: { fontSize: 11, fontWeight: 700, color: '#706e6b', textTransform: 'uppercase', letterSpacing: '0.06em' },
    statVal: { fontSize: 24, fontWeight: 700, color: '#080707', marginTop: 4, letterSpacing: '-0.01em' },
    statSub: { fontSize: 11, color: '#706e6b', marginTop: 2 },
  };

  // mini-trend sparkline (illustrative)
  const trendPath = "M0,18 L20,16 L40,18 L60,22 L80,21 L100,24 L120,28 L140,30 L160,33 L180,32 L200,36";

  return (
    <div style={heroStyles.card}>
      <div style={heroStyles.top}>
        <ScoreRing score={overallScore} size={140} stroke={12}/>
        <div style={heroStyles.score}>
          <div style={heroStyles.statLbl}>Overall OrgScore</div>
          <div style={{display:'flex', alignItems:'baseline'}}>
            <span style={heroStyles.big}>{Math.round(overallScore)}</span>
            <span style={heroStyles.out}>/ 100</span>
          </div>
          <div style={heroStyles.band(band)}>
            <Icon d={ICONS.warn} size={12}/>
            {band.label}
          </div>
        </div>
      </div>
      <div style={heroStyles.note}>
        Your org is in the bottom-risk band for <b>automation complexity</b> and <b>Agentforce readiness</b>. Fixing the top 9 P1 items would lift this score to <b>~72</b>.
      </div>
      <div style={{display:'flex', flexDirection:'column', gap: 8}}>
        <div style={heroStyles.statLbl}>30-day trend</div>
        <svg viewBox="0 0 200 44" style={{width: '100%', height: 44}}>
          <defs>
            <linearGradient id="trendFill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor="#c23934" stopOpacity="0.18"/>
              <stop offset="1" stopColor="#c23934" stopOpacity="0"/>
            </linearGradient>
          </defs>
          <path d={`${trendPath} L200,44 L0,44 Z`} fill="url(#trendFill)"/>
          <path d={trendPath} stroke="#c23934" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          <circle cx="200" cy="36" r="3" fill="#c23934"/>
        </svg>
        <div style={{fontSize: 11, color: '#706e6b'}}>Score down 7 points since April scan — driven by new legacy automation imports.</div>
      </div>
      <div style={heroStyles.stats}>
        <div style={heroStyles.stat}>
          <div style={heroStyles.statLbl}>P1 — Fix this sprint</div>
          <div style={{...heroStyles.statVal, color: '#ba0517'}}>{p1Count}</div>
          <div style={heroStyles.statSub}>operational + security risk</div>
        </div>
        <div style={heroStyles.stat}>
          <div style={heroStyles.statLbl}>P2 — Cleanup backlog</div>
          <div style={{...heroStyles.statVal, color: '#a96404'}}>{p2Count}</div>
          <div style={heroStyles.statSub}>schedule into next 60 days</div>
        </div>
      </div>
    </div>
  );
}

// ===== Category grid =====
function CategoryGrid({ categories, onNavigate }) {
  const meta = {
    data:       { icon: ICONS.field,     screen: 'backlog' },
    automation: { icon: ICONS.flow,      screen: 'automap' },
    security:   { icon: ICONS.lock,      screen: 'backlog' },
    apex:       { icon: ICONS.apex,      screen: 'backlog' },
    release:    { icon: ICONS.release,   screen: 'backlog' },
    ai:         { icon: ICONS.sparkle,   screen: 'ai'      },
  };

  return (
    <Card style={{padding: 0}}>
      <CardHeader
        eyebrow="Category breakdown"
        title="Where the score is bleeding"
        icon={ICONS.dashboard}
        action={<Btn variant="text" size="sm">View all categories <Icon d={ICONS.chevR} size={12}/></Btn>}
      />
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 0}}>
        {categories.map((cat, i) => {
          const m = meta[cat.id];
          const band = scoreBand(cat.score);
          const isRightCol = i % 2 === 1;
          const isLastRow = i >= categories.length - 2;
          return (
            <div key={cat.id} style={{
              padding: 16,
              borderRight: isRightCol ? 'none' : '1px solid #ecebea',
              borderBottom: isLastRow ? 'none' : '1px solid #ecebea',
              cursor: 'pointer', transition: 'background 150ms',
              display: 'flex', alignItems: 'center', gap: 14,
            }} onClick={() => m && onNavigate(m.screen)}
               onMouseEnter={e => e.currentTarget.style.background = '#fafaf9'}
               onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <ScoreRing score={cat.score} size={56} stroke={6}/>
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{
                  fontSize: 11, fontWeight: 700, color: '#706e6b',
                  textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 2,
                }}>
                  <Icon d={m.icon} size={11} style={{display:'inline-block', verticalAlign: '-2px', marginRight: 4, opacity: 0.8}}/>
                  {cat.label}
                </div>
                <div style={{display:'flex', alignItems:'center', gap: 6}}>
                  <div style={{fontSize: 18, fontWeight: 700, color: '#080707'}}>{cat.score}</div>
                  <TrendChip trend={cat.delta > 0 ? 'up' : cat.delta < 0 ? 'down' : 'flat'} delta={cat.delta}/>
                </div>
                <div style={{fontSize: 11, color: band.color, fontWeight: 700, marginTop: 2}}>{band.label}</div>
              </div>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

// ===== Top Findings list =====
function TopFindings({ findings, onOpenFinding, onNavigate }) {
  return (
    <Card style={{padding: 0}}>
      <CardHeader
        eyebrow="Top findings"
        title="What's driving risk right now"
        icon={ICONS.warn}
        action={<Btn variant="text" size="sm" onClick={() => onNavigate('backlog')}>Open Fix Backlog <Icon d={ICONS.chevR} size={12}/></Btn>}
      />
      <div>
        {findings.map((f, i) => {
          const catMeta = window.CATEGORY_META[f.category];
          return (
            <div key={f.id} onClick={() => onOpenFinding(f)} style={{
              display: 'grid',
              gridTemplateColumns: '32px 1fr auto auto',
              alignItems: 'center', gap: 12,
              padding: '14px 16px',
              borderBottom: i < findings.length - 1 ? '1px solid #ecebea' : 'none',
              cursor: 'pointer', transition: 'background 150ms',
            }} onMouseEnter={e => e.currentTarget.style.background = '#fafaf9'}
               onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <div style={{
                width: 32, height: 32, borderRadius: 4,
                background: catMeta.color, opacity: 0.95,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff',
              }}>
                <Icon d={ICONS.warn} size={16}/>
              </div>
              <div style={{minWidth: 0}}>
                <div style={{fontSize: 13, fontWeight: 700, color: '#080707', lineHeight: 1.3}}>
                  {f.title}
                </div>
                <div style={{fontSize: 11, color: '#706e6b', marginTop: 2}}>
                  {catMeta.label} · {f.object} · Confidence {f.confidence}%
                </div>
              </div>
              <div style={{textAlign:'right'}}>
                <div style={{fontSize: 11, fontWeight: 700, color: '#706e6b', textTransform: 'uppercase', letterSpacing: '0.04em'}}>Risk</div>
                <div style={{fontSize: 16, fontWeight: 700, color: scoreColor(100 - f.riskScore), letterSpacing: '-0.01em'}}>{f.riskScore}</div>
              </div>
              <PriorityPill priority={f.priority}/>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

// ===== Next Action card — the "what to do first" prompt =====
function NextActionCard({ openFindings, onNavigate, onOpenCopilot }) {
  const p1 = openFindings.filter(f => f.priority === 'P1').slice(0, 9);
  // Sum estimated hours from effortHours strings (rough estimate)
  const effortLow = p1.length * 1;
  const effortHigh = p1.length * 4;

  return (
    <Card style={{padding: 0, display: 'flex', flexDirection: 'column'}}>
      <CardHeader eyebrow="Recommended next action" title="Run the first sprint" icon={ICONS.play}/>
      <div style={{padding: 16, display: 'flex', flexDirection: 'column', gap: 12}}>
        <div style={{
          padding: 12, background: '#fce7e7', border: '1px solid #f6a9a5',
          borderRadius: 4, fontSize: 12, color: '#8e0c0c', lineHeight: 1.5,
        }}>
          <b>Critical:</b> 1 finding exposes 1.2M Contact records to guest users. Fix this in the next 24 hours.
        </div>
        <div style={{display:'flex', flexDirection: 'column', gap: 8}}>
          <div style={{fontSize: 12, color: '#3e3e3c', lineHeight: 1.5}}>
            Fix <b>{p1.length} P1 findings</b> on Opportunity, Case, and Guest User. Estimated effort:
          </div>
          <div style={{display:'flex', alignItems:'baseline', gap: 6}}>
            <span style={{fontSize: 28, fontWeight: 700, color: '#080707', letterSpacing: '-0.02em'}}>{effortLow}–{effortHigh}</span>
            <span style={{fontSize: 14, color: '#706e6b'}}>hours</span>
          </div>
          <div style={{fontSize: 12, color: '#706e6b'}}>Expected score lift: <b style={{color: '#2e844a'}}>+22 points</b></div>
        </div>
        <div style={{display:'flex', flexDirection: 'column', gap: 6, marginTop: 4}}>
          <Btn variant="brand" size="md" icon={ICONS.sparkle}
            onClick={() => onOpenCopilot && onOpenCopilot("Plan my next two-week sprint. Pick 5–8 findings from the P1 list that balance impact, effort, and ownership. For each, give: the finding ID, what it fixes, who owns it, and the expected score lift. Then summarize total estimated hours and total score lift.")}>
            Plan sprint with AI
          </Btn>
          <Btn variant="neutral" size="md" icon={ICONS.play} onClick={() => onNavigate('backlog')} style={{justifyContent:'center'}}>
            Open Fix Backlog
          </Btn>
          <Btn variant="neutral" size="md" icon={ICONS.jira} style={{justifyContent:'center'}}>
            Push to Jira / DevOps Center
          </Btn>
        </div>
      </div>
    </Card>
  );
}

// ===== ReleaseGuard cross-sell banner =====
function ReleaseGuardBanner({ visible = true }) {
  if (!visible) return null;
  return (
    <Card style={{
      marginTop: 16, padding: '14px 20px',
      display: 'flex', alignItems: 'center', gap: 16,
      background: 'linear-gradient(90deg, #032d60 0%, #0a4a8c 100%)',
      borderColor: '#032d60', color: '#fff',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 4,
        background: 'rgba(255,255,255,0.15)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
      }}>
        <Icon d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm-2 16l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 7z" size={20}/>
      </div>
      <div style={{flex: 1}}>
        <div style={{fontSize: 14, fontWeight: 700, lineHeight: 1.3}}>
          Pair OrgLens with ReleaseGuard AI for end-to-end org governance.
        </div>
        <div style={{fontSize: 12, color: 'rgba(255,255,255,0.75)', marginTop: 2}}>
          OrgLens finds the debt. ReleaseGuard makes sure new changes don't add more.
        </div>
      </div>
      <Btn variant="neutral" size="sm" style={{background: '#fff', color: '#0070d2', border: 'none'}}>
        Learn more <Icon d={ICONS.externalLink} size={12}/>
      </Btn>
    </Card>
  );
}

Object.assign(window, { Dashboard });
