// OrgLens — Fix Backlog (the money screen)

function FixBacklog({ findings, onOpenFinding, onSetStatus, activeOrg }) {
  const [filters, setFilters] = React.useState({
    priority: 'all',
    category: 'all',
    status: 'open',
    owner: 'all',
    quick: null, // quick-pill filters: 'high-risk', 'low-effort', 'admin-fixable', 'dev-needed', 'ai-readiness'
  });
  const [sortBy, setSortBy] = React.useState('risk');
  const [selected, setSelected] = React.useState(new Set());

  // Apply filters
  const filtered = React.useMemo(() => {
    let rows = [...findings];
    if (filters.status !== 'all')   rows = rows.filter(r => r.status === filters.status);
    if (filters.priority !== 'all') rows = rows.filter(r => r.priority === filters.priority);
    if (filters.category !== 'all') rows = rows.filter(r => r.category === filters.category);
    if (filters.owner === 'admin')  rows = rows.filter(r => r.owner === 'Admin' || r.owner === 'Admin + Business Owner');
    if (filters.owner === 'dev')    rows = rows.filter(r => r.owner === 'Dev' || r.owner === 'Admin + Dev');
    if (filters.quick === 'high-risk')     rows = rows.filter(r => r.riskScore >= 70);
    if (filters.quick === 'low-effort')    rows = rows.filter(r => r.effort === 'Low');
    if (filters.quick === 'admin-fixable') rows = rows.filter(r => r.owner.includes('Admin'));
    if (filters.quick === 'dev-needed')    rows = rows.filter(r => r.owner.includes('Dev'));
    if (filters.quick === 'ai-readiness')  rows = rows.filter(r => r.category === 'ai');

    if (sortBy === 'risk')     rows.sort((a,b) => b.riskScore - a.riskScore);
    if (sortBy === 'priority') rows.sort((a,b) => a.priority.localeCompare(b.priority));
    if (sortBy === 'effort')   rows.sort((a,b) => ({Low:1, Medium:2, High:3})[a.effort] - ({Low:1, Medium:2, High:3})[b.effort]);
    return rows;
  }, [findings, filters, sortBy]);

  const counts = {
    all:     findings.filter(f => f.status === 'open').length,
    p1:      findings.filter(f => f.priority === 'P1' && f.status === 'open').length,
    p2:      findings.filter(f => f.priority === 'P2' && f.status === 'open').length,
    p3:      findings.filter(f => f.priority === 'P3' && f.status === 'open').length,
    resolved: findings.filter(f => f.status === 'resolved').length,
    ignored: findings.filter(f => f.status === 'ignored').length,
  };

  const toggleRow = (id) => {
    setSelected(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const bulkMark = (newStatus) => {
    selected.forEach(id => onSetStatus(id, newStatus));
    setSelected(new Set());
  };

  const backlogStyles = {
    page: { flex: 1, overflow: 'auto', background: '#f3f2f2', padding: 16, display: 'flex', flexDirection: 'column', gap: 12 },
    pageHeader: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', 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 },
  };

  return (
    <div style={backlogStyles.page}>
      <div style={backlogStyles.pageHeader}>
        <div style={backlogStyles.titleWrap}>
          <div style={backlogStyles.eyebrow}>Fix Backlog · {activeOrg.name}</div>
          <div style={backlogStyles.title}>
            {counts.all} active findings · <span style={{color:'#ba0517'}}>{counts.p1} P1</span> · <span style={{color:'#a96404'}}>{counts.p2} P2</span> · {counts.p3} P3
          </div>
          <div style={backlogStyles.sub}>
            {counts.resolved} resolved · {counts.ignored} accepted risk. Filter, prioritize, and push to your tracker.
          </div>
        </div>
        <div style={{display:'flex', gap: 8}}>
          <Btn variant="neutral" icon={ICONS.download}>Export CSV</Btn>
          <Btn variant="brand" icon={ICONS.jira}>Push selected to Jira</Btn>
        </div>
      </div>

      <QuickFilterRow filters={filters} setFilters={setFilters}/>
      <FilterToolbar filters={filters} setFilters={setFilters} sortBy={sortBy} setSortBy={setSortBy} counts={counts}/>

      {selected.size > 0 && (
        <BulkBar
          count={selected.size}
          onMarkResolved={() => bulkMark('resolved')}
          onMarkIgnored={() => bulkMark('ignored')}
          onClear={() => setSelected(new Set())}
        />
      )}

      <BacklogTable
        findings={filtered}
        onOpenFinding={onOpenFinding}
        onSetStatus={onSetStatus}
        selected={selected}
        onToggleRow={toggleRow}
      />
    </div>
  );
}

// ===== Quick filter pills =====
function QuickFilterRow({ filters, setFilters }) {
  const pills = [
    { id: 'high-risk',     label: 'High risk',      icon: ICONS.warn },
    { id: 'low-effort',    label: 'Low effort',     icon: ICONS.check },
    { id: 'admin-fixable', label: 'Admin fixable',  icon: ICONS.user },
    { id: 'dev-needed',    label: 'Developer needed', icon: ICONS.apex },
    { id: 'ai-readiness',  label: 'AI readiness',   icon: ICONS.sparkle },
  ];
  return (
    <div style={{display: 'flex', gap: 8, flexWrap: 'wrap'}}>
      {pills.map(p => {
        const active = filters.quick === p.id;
        return (
          <button key={p.id} onClick={() => setFilters(f => ({...f, quick: active ? null : p.id}))} style={{
            height: 30, padding: '0 12px', borderRadius: 999, cursor: 'pointer',
            fontFamily: 'inherit', fontSize: 12, fontWeight: 600,
            background: active ? '#0070d2' : '#fff',
            color: active ? '#fff' : '#3e3e3c',
            border: active ? '1px solid #0070d2' : '1px solid #dddbda',
            display: 'inline-flex', alignItems: 'center', gap: 6, transition: 'all 150ms',
          }}>
            <Icon d={p.icon} size={12}/>{p.label}
          </button>
        );
      })}
    </div>
  );
}

// ===== Filter toolbar =====
function FilterToolbar({ filters, setFilters, sortBy, setSortBy, counts }) {
  const selectStyle = {
    height: 32, padding: '0 28px 0 10px', borderRadius: 4,
    border: '1px solid #dddbda', background: '#fff',
    fontSize: 13, fontFamily: 'inherit', color: '#080707',
    appearance: 'none',
    backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='%23706e6b'%3E%3Cpath d='M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6-1.41-1.41z'/%3E%3C/svg%3E\")",
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'right 10px center',
    cursor: 'pointer', outline: 'none',
  };
  const lbl = { fontSize: 11, fontWeight: 700, color: '#706e6b', textTransform: 'uppercase', letterSpacing: '0.04em' };

  return (
    <Card style={{padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap'}}>
      <div style={{display:'flex', alignItems:'center', gap: 4}}>
        <Icon d={ICONS.filter} size={14} color="#706e6b"/>
        <span style={lbl}>Filter</span>
      </div>
      <div style={{display:'flex', alignItems:'center', gap: 6}}>
        <span style={{fontSize: 12, color: '#3e3e3c'}}>Priority</span>
        <select style={selectStyle} value={filters.priority} onChange={e => setFilters(f => ({...f, priority: e.target.value}))}>
          <option value="all">All ({counts.all})</option>
          <option value="P1">P1 ({counts.p1})</option>
          <option value="P2">P2 ({counts.p2})</option>
          <option value="P3">P3 ({counts.p3})</option>
        </select>
      </div>
      <div style={{display:'flex', alignItems:'center', gap: 6}}>
        <span style={{fontSize: 12, color: '#3e3e3c'}}>Category</span>
        <select style={selectStyle} value={filters.category} onChange={e => setFilters(f => ({...f, category: e.target.value}))}>
          <option value="all">All</option>
          <option value="automation">Automation</option>
          <option value="data">Data model</option>
          <option value="security">Security & access</option>
          <option value="apex">Apex & tests</option>
          <option value="release">Release readiness</option>
          <option value="ai">Agentforce readiness</option>
        </select>
      </div>
      <div style={{display:'flex', alignItems:'center', gap: 6}}>
        <span style={{fontSize: 12, color: '#3e3e3c'}}>Owner</span>
        <select style={selectStyle} value={filters.owner} onChange={e => setFilters(f => ({...f, owner: e.target.value}))}>
          <option value="all">Anyone</option>
          <option value="admin">Admin</option>
          <option value="dev">Developer</option>
        </select>
      </div>
      <div style={{display:'flex', alignItems:'center', gap: 6}}>
        <span style={{fontSize: 12, color: '#3e3e3c'}}>Status</span>
        <select style={selectStyle} value={filters.status} onChange={e => setFilters(f => ({...f, status: e.target.value}))}>
          <option value="open">Open</option>
          <option value="resolved">Resolved</option>
          <option value="ignored">Accepted risk</option>
          <option value="all">All</option>
        </select>
      </div>
      <div style={{marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 6}}>
        <span style={{fontSize: 12, color: '#3e3e3c'}}>Sort</span>
        <select style={selectStyle} value={sortBy} onChange={e => setSortBy(e.target.value)}>
          <option value="risk">Risk score</option>
          <option value="priority">Priority</option>
          <option value="effort">Effort (low first)</option>
        </select>
      </div>
    </Card>
  );
}

// ===== Bulk action bar =====
function BulkBar({ count, onMarkResolved, onMarkIgnored, onClear }) {
  return (
    <div style={{
      background: '#032d60', color: '#fff',
      borderRadius: 4, padding: '10px 14px',
      display: 'flex', alignItems: 'center', gap: 12,
      boxShadow: '0 2px 4px rgba(0,0,0,0.12)',
    }}>
      <div style={{fontSize: 13, fontWeight: 700}}>{count} selected</div>
      <div style={{height: 20, width: 1, background: 'rgba(255,255,255,0.25)'}}/>
      <button onClick={onMarkResolved} style={{
        height: 28, padding: '0 12px', borderRadius: 4, cursor: 'pointer',
        background: '#3ba755', color: '#fff', border: 'none', fontFamily: 'inherit',
        fontSize: 12, fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 6,
      }}>
        <Icon d={ICONS.check} size={12}/>Mark resolved
      </button>
      <button onClick={onMarkIgnored} style={{
        height: 28, padding: '0 12px', borderRadius: 4, cursor: 'pointer',
        background: 'rgba(255,255,255,0.15)', color: '#fff', border: '1px solid rgba(255,255,255,0.3)', fontFamily: 'inherit',
        fontSize: 12, fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 6,
      }}>
        <Icon d={ICONS.close} size={12}/>Accept risk
      </button>
      <button style={{
        height: 28, padding: '0 12px', borderRadius: 4, cursor: 'pointer',
        background: 'rgba(255,255,255,0.15)', color: '#fff', border: '1px solid rgba(255,255,255,0.3)', fontFamily: 'inherit',
        fontSize: 12, fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 6,
      }}>
        <Icon d={ICONS.jira} size={12}/>Push to Jira
      </button>
      <button onClick={onClear} style={{
        marginLeft: 'auto',
        background: 'none', color: 'rgba(255,255,255,0.8)', border: 'none',
        cursor: 'pointer', fontSize: 12, fontFamily: 'inherit',
      }}>Clear selection</button>
    </div>
  );
}

// ===== Backlog table =====
function BacklogTable({ findings, onOpenFinding, onSetStatus, selected, onToggleRow }) {
  const cellStyle = {
    padding: '12px 12px', fontSize: 13, color: '#080707',
    borderBottom: '1px solid #ecebea', verticalAlign: 'middle',
  };
  const thStyle = {
    padding: '8px 12px', fontSize: 11, fontWeight: 700, color: '#706e6b',
    textTransform: 'uppercase', letterSpacing: '0.05em',
    textAlign: 'left', borderBottom: '1px solid #dddbda',
    background: '#fafaf9', whiteSpace: 'nowrap',
  };

  if (findings.length === 0) {
    return (
      <Card style={{padding: 60, textAlign: 'center'}}>
        <Icon d={ICONS.check} size={32} color="#3ba755"/>
        <div style={{fontSize: 18, fontWeight: 700, marginTop: 12, color: '#080707'}}>Nothing here</div>
        <div style={{fontSize: 13, color: '#706e6b', marginTop: 4}}>No findings match these filters. Try widening your selection.</div>
      </Card>
    );
  }

  return (
    <Card style={{padding: 0, overflow: 'hidden'}}>
      <div style={{overflowX: 'auto'}}>
        <table style={{width: '100%', borderCollapse: 'collapse'}}>
          <thead>
            <tr>
              <th style={{...thStyle, width: 32}}></th>
              <th style={{...thStyle, width: 56}}>Priority</th>
              <th style={thStyle}>Finding</th>
              <th style={{...thStyle, width: 110}}>Category</th>
              <th style={{...thStyle, width: 80, textAlign: 'right'}}>Risk</th>
              <th style={{...thStyle, width: 90}}>Impact</th>
              <th style={{...thStyle, width: 90}}>Effort</th>
              <th style={{...thStyle, width: 130}}>Owner</th>
              <th style={{...thStyle, width: 40}}></th>
            </tr>
          </thead>
          <tbody>
            {findings.map(f => {
              const catMeta = window.CATEGORY_META[f.category];
              const isResolved = f.status === 'resolved';
              const isIgnored  = f.status === 'ignored';
              return (
                <tr key={f.id} style={{
                  cursor: 'pointer', transition: 'background 150ms',
                  background: selected.has(f.id) ? '#eaf4ff' : 'transparent',
                  opacity: isResolved || isIgnored ? 0.55 : 1,
                }}
                  onMouseEnter={e => { if (!selected.has(f.id)) e.currentTarget.style.background = '#fafaf9'; }}
                  onMouseLeave={e => { if (!selected.has(f.id)) e.currentTarget.style.background = 'transparent'; }}
                  onClick={() => onOpenFinding(f)}>
                  <td style={cellStyle} onClick={e => { e.stopPropagation(); onToggleRow(f.id); }}>
                    <input type="checkbox" checked={selected.has(f.id)} readOnly
                      style={{accentColor: '#0070d2', cursor: 'pointer'}}/>
                  </td>
                  <td style={cellStyle}><PriorityPill priority={f.priority}/></td>
                  <td style={cellStyle}>
                    <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
                      <div>
                        <div style={{fontWeight: 700, color: '#080707', textDecoration: isResolved ? 'line-through' : 'none'}}>
                          {f.title}
                        </div>
                        <div style={{fontSize: 11, color: '#706e6b', marginTop: 2}}>
                          {f.id} · {f.object} · Confidence {f.confidence}%
                          {isResolved && <span style={{color:'#2e844a', fontWeight: 700, marginLeft: 6}}>· RESOLVED</span>}
                          {isIgnored && <span style={{color:'#706e6b', fontWeight: 700, marginLeft: 6}}>· ACCEPTED RISK</span>}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td style={cellStyle}>
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      fontSize: 12, color: '#3e3e3c',
                    }}>
                      <span style={{width: 8, height: 8, borderRadius: 2, background: catMeta.color}}/>
                      {catMeta.label}
                    </span>
                  </td>
                  <td style={{...cellStyle, textAlign: 'right'}}>
                    <div style={{display: 'inline-flex', alignItems: 'center', gap: 6, justifyContent: 'flex-end'}}>
                      <span style={{fontWeight: 700, color: '#080707'}}>{f.riskScore}</span>
                      <div style={{width: 36, height: 4, background: '#ecebea', borderRadius: 999, overflow: 'hidden'}}>
                        <div style={{width: `${f.riskScore}%`, height: '100%', background: scoreColor(100 - f.riskScore)}}/>
                      </div>
                    </div>
                  </td>
                  <td style={cellStyle}>
                    <ImpactTag impact={f.impact}/>
                  </td>
                  <td style={cellStyle}>
                    <span style={{fontSize: 12, color: '#3e3e3c'}}>{f.effort}<span style={{color:'#706e6b', marginLeft: 4}}>· {f.effortHours}</span></span>
                  </td>
                  <td style={cellStyle}><span style={{fontSize: 12, color: '#3e3e3c'}}>{f.owner}</span></td>
                  <td style={cellStyle}>
                    <button style={{
                      background: 'none', border: 'none', cursor: 'pointer',
                      width: 24, height: 24, borderRadius: 4,
                      display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#706e6b',
                    }}><Icon d={ICONS.chevR} size={14}/></button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

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

Object.assign(window, { FixBacklog });
