// OrgLens — Issue Drawer (slide-out remediation panel)

function IssueDrawer({ finding, onClose, onSetStatus, onShowToast }) {
  if (!finding) return null;
  const catMeta = window.CATEGORY_META[finding.category];

  // AI-generated artifacts (per-finding, session-scoped)
  const [aiFix, setAiFix] = React.useState(null);     // { loading, content, error }
  const [aiJira, setAiJira] = React.useState(null);   // { loading, content, error }
  const aiSectionRef = React.useRef(null);

  // Reset AI state when finding changes
  React.useEffect(() => { setAiFix(null); setAiJira(null); }, [finding && finding.id]);

  const callClaude = async (kind, prompt) => {
    const setter = kind === 'fix' ? setAiFix : setAiJira;
    setter({ loading: true, content: '' });
    // Scroll the AI section into view after a tick
    setTimeout(() => {
      if (aiSectionRef.current) {
        aiSectionRef.current.scrollIntoView ? null : null; // no-op, intentionally avoid scrollIntoView
      }
    }, 50);
    try {
      const ctx = `You are an expert Salesforce admin/developer assistant inside OrgLens, a Salesforce org health product.

Finding context:
- ID: ${finding.id}
- Title: ${finding.title}
- Category: ${catMeta.label}
- Object: ${finding.object}
- Priority: ${finding.priority} (Severity: ${finding.severity})
- Risk score: ${finding.riskScore}/100
- Blast radius: ${finding.blastRadius}
- Confidence: ${finding.confidence}%
- Effort: ${finding.effort} (${finding.effortHours})
- Suggested owner: ${finding.owner}
- Why it matters: ${finding.why}
- Evidence:
${finding.evidence.map(e => `  - ${e}`).join('\n')}
- Recommended fix (high-level): ${finding.fix}

${prompt}`;
      const response = await window.claude.complete({
        messages: [{ role: 'user', content: ctx }],
      });
      setter({ loading: false, content: response });
    } catch (err) {
      setter({ loading: false, error: 'Could not reach the AI service. Try again.' });
    }
  };

  const drawerStyles = {
    backdrop: {
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.32)',
      zIndex: 7000, animation: 'fadeIn 200ms cubic-bezier(0.4,0,0.2,1)',
    },
    panel: {
      position: 'fixed', top: 0, right: 0, bottom: 0,
      width: 'min(640px, 92vw)', background: '#fff',
      boxShadow: '-4px 0 24px rgba(0,0,0,0.18)',
      zIndex: 7001, display: 'flex', flexDirection: 'column',
      animation: 'slideInRight 240ms cubic-bezier(0.4,0,0.2,1)',
    },
    header: {
      padding: '16px 20px', borderBottom: '1px solid #dddbda',
      display: 'flex', alignItems: 'flex-start', gap: 12, flexShrink: 0,
    },
    body: { flex: 1, overflow: 'auto', padding: 20 },
    footer: {
      padding: '12px 20px', borderTop: '1px solid #dddbda',
      display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0, flexWrap: 'wrap',
    },
    section: { marginBottom: 24 },
    sectionLbl: {
      fontSize: 11, fontWeight: 700, color: '#706e6b',
      textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8,
    },
    meta: {
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12,
      padding: 14, background: '#fafaf9', borderRadius: 4, border: '1px solid #ecebea',
      marginBottom: 20,
    },
    metaCell: {},
    metaLbl: { fontSize: 10, fontWeight: 700, color: '#706e6b', textTransform: 'uppercase', letterSpacing: '0.06em' },
    metaVal: { fontSize: 14, fontWeight: 700, color: '#080707', marginTop: 4, letterSpacing: '-0.005em' },
  };

  const handleAction = (action) => {
    if (action === 'resolved') {
      onSetStatus(finding.id, 'resolved');
      onShowToast(`Finding ${finding.id} marked resolved. OrgScore updated.`, 'success');
      onClose();
    } else if (action === 'ignored') {
      onSetStatus(finding.id, 'ignored');
      onShowToast(`Finding ${finding.id} accepted as risk for 90 days.`, 'info');
      onClose();
    } else if (action === 'fix-instructions') {
      callClaude('fix',
        `Generate a detailed, step-by-step fix plan for this finding. Format:

## Goal
One-sentence goal.

## Steps
A numbered list. Each step is one concrete action an admin or developer can perform. Reference specific Setup paths, API names, or code locations where possible. Include validation checks between risky steps.

## Acceptance criteria
A short bullet list — how do we know the fix worked?

## Rollback plan
2–3 bullets — how to revert if it goes wrong.

Be direct. Plain language. No emoji. No filler.`);
    } else if (action === 'jira') {
      callClaude('jira',
        `Draft a Jira story for this finding. Format:

## Title
A concise one-line title in the form: "[${finding.object}] verb-led action — outcome"

## Description
2–3 short paragraphs: what the problem is, why it matters to the business, and what we're going to do.

## Acceptance criteria
Bulleted list (3–6 items).

## Definition of done
Bulleted list (2–4 items).

## Story points
A number (1, 2, 3, 5, 8, or 13) with one-sentence justification.

## Labels
A short comma-separated list (e.g. tech-debt, agentforce-readiness, automation).

Use plain English. No emoji.`);
    }
  };

  return (
    <>
      <div style={drawerStyles.backdrop} onClick={onClose}/>
      <div style={drawerStyles.panel} onClick={e => e.stopPropagation()}>
        <div style={drawerStyles.header}>
          <div style={{
            width: 40, height: 40, borderRadius: 4, background: catMeta.color, opacity: 0.95,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', flexShrink: 0,
          }}>
            <Icon d={ICONS.warn} size={20}/>
          </div>
          <div style={{flex: 1, minWidth: 0}}>
            <div style={{display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4}}>
              <span style={{fontSize: 11, fontWeight: 700, color: '#706e6b', textTransform: 'uppercase', letterSpacing: '0.05em'}}>
                {finding.id} · {catMeta.label}
              </span>
              <PriorityPill priority={finding.priority}/>
            </div>
            <div style={{fontSize: 18, fontWeight: 700, color: '#080707', lineHeight: 1.3, letterSpacing: '-0.005em'}}>
              {finding.title}
            </div>
          </div>
          <button onClick={onClose} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            color: '#706e6b', padding: 6, display: 'flex',
            borderRadius: 4, flexShrink: 0,
          }}><Icon d={ICONS.close} size={18}/></button>
        </div>

        <div style={drawerStyles.body}>
          {/* Meta row */}
          <div style={drawerStyles.meta}>
            <div style={drawerStyles.metaCell}>
              <div style={drawerStyles.metaLbl}>Severity</div>
              <div style={{...drawerStyles.metaVal, color: finding.severity === 'Critical' ? '#8e0c0c' : finding.severity === 'High' ? '#ba0517' : '#a96404'}}>{finding.severity}</div>
            </div>
            <div style={drawerStyles.metaCell}>
              <div style={drawerStyles.metaLbl}>Risk score</div>
              <div style={drawerStyles.metaVal}>{finding.riskScore}/100</div>
            </div>
            <div style={drawerStyles.metaCell}>
              <div style={drawerStyles.metaLbl}>Object</div>
              <div style={drawerStyles.metaVal}>{finding.object}</div>
            </div>
            <div style={drawerStyles.metaCell}>
              <div style={drawerStyles.metaLbl}>Confidence</div>
              <div style={drawerStyles.metaVal}>{finding.confidence}%</div>
            </div>
            <div style={drawerStyles.metaCell}>
              <div style={drawerStyles.metaLbl}>Blast radius</div>
              <div style={drawerStyles.metaVal}>{finding.blastRadius}</div>
            </div>
            <div style={drawerStyles.metaCell}>
              <div style={drawerStyles.metaLbl}>Effort</div>
              <div style={drawerStyles.metaVal}>{finding.effort}<span style={{fontWeight: 400, fontSize: 12, color: '#706e6b', marginLeft: 4}}>· {finding.effortHours}</span></div>
            </div>
            <div style={drawerStyles.metaCell}>
              <div style={drawerStyles.metaLbl}>Suggested owner</div>
              <div style={drawerStyles.metaVal}>{finding.owner}</div>
            </div>
            <div style={drawerStyles.metaCell}>
              <div style={drawerStyles.metaLbl}>Detected in</div>
              <div style={drawerStyles.metaVal}>Production</div>
            </div>
          </div>

          {/* Why */}
          <div style={drawerStyles.section}>
            <div style={drawerStyles.sectionLbl}>Why this matters</div>
            <div style={{
              fontSize: 14, color: '#080707', lineHeight: 1.6,
              padding: 14, background: '#fffaef', border: '1px solid #fcb95b',
              borderRadius: 4,
            }}>{finding.why}</div>
          </div>

          {/* Evidence */}
          <div style={drawerStyles.section}>
            <div style={drawerStyles.sectionLbl}>Evidence ({finding.evidence.length} signal{finding.evidence.length > 1 ? 's' : ''})</div>
            <div style={{
              border: '1px solid #ecebea', borderRadius: 4, overflow: 'hidden',
              fontFamily: 'SFMono-Regular, Consolas, monospace', fontSize: 12,
            }}>
              {finding.evidence.map((line, i) => (
                <div key={i} style={{
                  padding: '8px 12px', color: '#3e3e3c',
                  borderBottom: i < finding.evidence.length - 1 ? '1px solid #ecebea' : 'none',
                  background: i % 2 === 0 ? '#fafaf9' : '#fff',
                  display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <span style={{
                    width: 14, height: 14, borderRadius: '50%',
                    background: '#ecebea', color: '#706e6b',
                    fontSize: 9, fontWeight: 700,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>{i + 1}</span>
                  {line}
                </div>
              ))}
            </div>
          </div>

          {/* Recommended fix */}
          <div style={drawerStyles.section}>
            <div style={drawerStyles.sectionLbl}>Recommended fix</div>
            <div style={{
              padding: 14, background: '#f3fbf2', border: '1px solid #91db8b',
              borderRadius: 4, fontSize: 14, color: '#080707', lineHeight: 1.6,
            }}>{finding.fix}</div>
          </div>

          {/* AI-generated artifacts */}
          {(aiFix || aiJira) && (
            <div ref={aiSectionRef}>
              {aiFix && <AIArtifactBlock title="AI fix plan" subtitle="Generated for this finding" content={aiFix} onCopy={() => { navigator.clipboard.writeText(aiFix.content || ''); onShowToast('Fix plan copied to clipboard.', 'success'); }}/>}
              {aiJira && <AIArtifactBlock title="Drafted Jira story" subtitle="Ready to paste into your tracker" content={aiJira} onCopy={() => { navigator.clipboard.writeText(aiJira.content || ''); onShowToast('Jira story copied to clipboard.', 'success'); }}/>}
            </div>
          )}

          {/* Score model */}
          <div style={drawerStyles.section}>
            <div style={drawerStyles.sectionLbl}>How we scored this</div>
            <ScoreFactorBars finding={finding}/>
          </div>
        </div>

        <div style={drawerStyles.footer}>
          <Btn variant="brand" icon={ICONS.sparkle}
            onClick={() => handleAction('fix-instructions')}
            disabled={aiFix && aiFix.loading}
            style={aiFix && aiFix.loading ? {opacity: 0.7, cursor: 'wait'} : {}}>
            {aiFix && aiFix.loading ? 'Generating…' : aiFix && aiFix.content ? 'Regenerate fix plan' : 'Generate fix plan'}
          </Btn>
          <Btn variant="neutral" icon={ICONS.jira}
            onClick={() => handleAction('jira')}
            disabled={aiJira && aiJira.loading}
            style={aiJira && aiJira.loading ? {opacity: 0.7, cursor: 'wait'} : {}}>
            {aiJira && aiJira.loading ? 'Drafting…' : aiJira && aiJira.content ? 'Redraft Jira story' : 'Draft Jira story'}
          </Btn>
          <Btn variant="neutral" icon={ICONS.user}>Assign owner</Btn>
          <div style={{flex: 1}}/>
          <Btn variant="destructive" icon={ICONS.close} onClick={() => handleAction('ignored')}>
            Accept risk
          </Btn>
          <Btn variant="neutral" icon={ICONS.check} style={{borderColor: '#3ba755', color: '#2e844a'}} onClick={() => handleAction('resolved')}>
            Mark resolved
          </Btn>
        </div>
      </div>
    </>
  );
}

function ScoreFactorBars({ finding }) {
  // Translate the priority math into illustrative bars
  const sevVal = finding.severity === 'Critical' ? 100 : finding.severity === 'High' ? 80 : finding.severity === 'Medium' ? 55 : 30;
  const blastVal = finding.blastRadius === 'Global' ? 100 : finding.blastRadius === 'Object-level' ? 70 : finding.blastRadius === 'User-group' ? 50 : 35;
  const usageVal = 70; // simulated "used" weight
  const sensVal = finding.object === 'Opportunity' || finding.object === 'Account' || finding.object === 'Case' || finding.object === 'Contact' || finding.object === 'Guest User' ? 85 : 60;
  const confVal = finding.confidence;
  const effortPenalty = finding.effort === 'High' ? 20 : finding.effort === 'Medium' ? 10 : 0;

  const factors = [
    { label: 'Severity',                value: sevVal,    color: '#c23934' },
    { label: 'Blast radius',            value: blastVal,  color: '#dd7a01' },
    { label: 'Usage weight',            value: usageVal,  color: '#0070d2' },
    { label: 'Business object sensitivity', value: sensVal, color: '#7f8de1' },
    { label: 'Confidence',              value: confVal,   color: '#3ba755' },
    { label: 'Effort penalty',          value: effortPenalty, color: '#706e6b' },
  ];
  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
      {factors.map(f => (
        <div key={f.label} style={{display: 'flex', alignItems: 'center', gap: 12}}>
          <div style={{width: 200, fontSize: 12, color: '#3e3e3c'}}>{f.label}</div>
          <div style={{flex: 1}}>
            <HBar value={f.value} color={f.color} height={6}/>
          </div>
          <div style={{width: 28, textAlign: 'right', fontSize: 12, fontWeight: 700, color: '#3e3e3c'}}>{f.value}</div>
        </div>
      ))}
      <div style={{
        marginTop: 8, padding: 10, background: '#fafaf9', border: '1px solid #ecebea',
        borderRadius: 4, fontSize: 12, color: '#3e3e3c', lineHeight: 1.5,
      }}>
        Priority = Severity × Blast × Usage × Sensitivity × Confidence – Effort penalty
        → <b style={{color: '#080707'}}>{finding.riskScore}</b> places this in <b style={{color: window.PRIORITY_META[finding.priority].color}}>{finding.priority}</b>.
      </div>
    </div>
  );
}

// ===== AI artifact block — renders the AI-generated fix plan or Jira story =====
function AIArtifactBlock({ title, subtitle, content, onCopy }) {
  const c = content || {};
  return (
    <div style={{marginBottom: 24}}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8,
      }}>
        <div style={{
          width: 22, height: 22, borderRadius: 4,
          background: 'linear-gradient(135deg, #032d60 0%, #0070d2 100%)',
          color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}><Icon d={ICONS.sparkle} size={11}/></div>
        <div style={{
          fontSize: 11, fontWeight: 700, color: '#706e6b',
          textTransform: 'uppercase', letterSpacing: '0.06em',
        }}>{title}</div>
        <span style={{fontSize: 11, color: '#706e6b', fontWeight: 400}}>· {subtitle}</span>
        {!c.loading && c.content && (
          <button onClick={onCopy} style={{
            marginLeft: 'auto', background: 'none', border: '1px solid #dddbda',
            borderRadius: 4, padding: '2px 8px', cursor: 'pointer', fontFamily: 'inherit',
            fontSize: 11, fontWeight: 700, color: '#3e3e3c',
            display: 'inline-flex', alignItems: 'center', gap: 4,
          }}>
            <Icon d={ICONS.download} size={10}/>Copy
          </button>
        )}
      </div>
      <div style={{
        border: '1px solid #c9dff4', borderRadius: 4,
        background: 'linear-gradient(180deg, #eaf4ff 0%, #fff 24px)',
        padding: 16, fontSize: 13,
      }}>
        {c.loading && (
          <div style={{display:'flex', alignItems:'center', gap: 8, color: '#3e3e3c', padding: '12px 0'}}>
            <div style={{display: 'flex', gap: 4}}>
              {[0, 1, 2].map(i => (
                <span key={i} style={{
                  width: 6, height: 6, borderRadius: '50%', background: '#0070d2',
                  animation: `bounce 1.2s ${i * 0.15}s infinite ease-in-out`,
                }}/>
              ))}
            </div>
            <span style={{fontSize: 12, color: '#706e6b'}}>OrgLens AI is analyzing this finding…</span>
            <style>{`@keyframes bounce { 0%, 80%, 100% { transform: scale(0.6); opacity: 0.5; } 40% { transform: scale(1); opacity: 1; } }`}</style>
          </div>
        )}
        {c.error && (
          <div style={{
            padding: 10, background: '#fce7e7', border: '1px solid #f6a9a5',
            borderRadius: 4, fontSize: 12, color: '#8e0c0c',
          }}>{c.error}</div>
        )}
        {!c.loading && !c.error && c.content && (
          <div className="ai-artifact-content">
            {window.renderMarkdown ? window.renderMarkdown(c.content) : <pre style={{whiteSpace: 'pre-wrap'}}>{c.content}</pre>}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { IssueDrawer, AIArtifactBlock });
