// OrgLens — Automation Map

function AutomationMap({ map, onOpenFinding, findings }) {
  const [selectedObject, setSelectedObject] = React.useState('Opportunity');

  const automapStyles = {
    page: { flex: 1, overflow: 'auto', background: '#f3f2f2', padding: 16 },
    header: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 16, gap: 16 },
    title: { fontSize: 22, fontWeight: 700, color: '#080707', letterSpacing: '-0.01em' },
    sub: { fontSize: 13, color: '#3e3e3c', marginTop: 4 },
    eyebrow: { fontSize: 11, fontWeight: 700, color: '#706e6b', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 },
    grid: { display: 'grid', gridTemplateColumns: '220px 1fr', gap: 16 },
  };

  // Object list with automation counts
  const objects = [
    { name: 'Opportunity', total: 7,  health: 'error' },
    { name: 'Account',     total: 5,  health: 'warn'  },
    { name: 'Contact',     total: 4,  health: 'warn'  },
    { name: 'Case',        total: 6,  health: 'error' },
    { name: 'Lead',        total: 5,  health: 'warn'  },
    { name: 'Quote',       total: 2,  health: 'ok'    },
    { name: 'Contract',    total: 3,  health: 'ok'    },
  ];

  return (
    <div style={automapStyles.page}>
      <div style={automapStyles.header}>
        <div>
          <div style={automapStyles.eyebrow}>Automation Map</div>
          <div style={automapStyles.title}>Visualize what runs when records change</div>
          <div style={automapStyles.sub}>
            Trace Triggers, Flows, Workflow Rules, and Process Builders on a single object's save cycle.
          </div>
        </div>
        <div style={{display:'flex', gap: 8}}>
          <Btn variant="neutral" icon={ICONS.download}>Export diagram</Btn>
          <Btn variant="neutral" icon={ICONS.flow}>Open in Schema Builder</Btn>
        </div>
      </div>

      <div style={automapStyles.grid}>
        <ObjectPicker objects={objects} selected={selectedObject} onSelect={setSelectedObject}/>
        <AutomationLanes map={map} onOpenFinding={onOpenFinding} findings={findings}/>
      </div>
    </div>
  );
}

function ObjectPicker({ objects, selected, onSelect }) {
  return (
    <Card style={{padding: 0, alignSelf: 'flex-start'}}>
      <div style={{
        padding: '10px 14px', borderBottom: '1px solid #dddbda',
        fontSize: 11, fontWeight: 700, color: '#706e6b',
        textTransform: 'uppercase', letterSpacing: '0.06em',
      }}>Objects ({objects.length})</div>
      <div>
        {objects.map((o, i) => {
          const isActive = o.name === selected;
          const dotColor = o.health === 'error' ? '#c23934' : o.health === 'warn' ? '#dd7a01' : '#3ba755';
          return (
            <div key={o.name} onClick={() => onSelect(o.name)} style={{
              padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
              cursor: 'pointer', borderBottom: i < objects.length - 1 ? '1px solid #ecebea' : 'none',
              background: isActive ? '#eaf4ff' : 'transparent',
              borderLeft: isActive ? '3px solid #0070d2' : '3px solid transparent',
              transition: 'background 150ms',
            }} onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = '#fafaf9'; }}
               onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}>
              <span style={{width: 8, height: 8, borderRadius: '50%', background: dotColor, flexShrink: 0}}/>
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontSize: 13, fontWeight: isActive ? 700 : 600, color: '#080707'}}>{o.name}</div>
                <div style={{fontSize: 11, color: '#706e6b', marginTop: 1}}>{o.total} automation{o.total>1?'s':''}</div>
              </div>
              {isActive && <Icon d={ICONS.chevR} size={12} color="#0070d2"/>}
            </div>
          );
        })}
      </div>
    </Card>
  );
}

function AutomationLanes({ map, onOpenFinding, findings }) {
  // Find related findings to surface
  const related = findings.filter(f => f.category === 'automation' && (f.object === map.object || f.object === 'Multiple')).slice(0, 4);

  return (
    <Card style={{padding: 0}}>
      <CardHeader
        eyebrow={`Order of execution · ${map.object}`}
        title={`${map.riskNote}`}
        icon={ICONS.map}
        action={
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            height: 26, padding: '0 10px', borderRadius: 4,
            background: '#fce7e7', color: '#ba0517',
            fontSize: 12, fontWeight: 700,
          }}>
            <Icon d={ICONS.warn} size={12}/>
            {map.riskLevel} risk
          </span>
        }
      />

      {/* The lanes diagram */}
      <div style={{padding: 20, background: 'linear-gradient(180deg, #fafaf9 0%, #fff 100%)'}}>
        <LaneFlow lanes={map.lanes} onOpenFinding={onOpenFinding} findings={findings} object={map.object}/>
      </div>

      {/* Related findings strip */}
      <div style={{borderTop: '1px solid #ecebea', padding: '12px 16px', background: '#fafaf9'}}>
        <div style={{
          fontSize: 11, fontWeight: 700, color: '#706e6b',
          textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8,
        }}>Related findings on {map.object}</div>
        <div style={{display: 'flex', flexDirection: 'column', gap: 6}}>
          {related.map(f => (
            <div key={f.id} onClick={() => onOpenFinding(f)} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '8px 10px', background: '#fff', border: '1px solid #ecebea',
              borderRadius: 4, cursor: 'pointer',
            }} onMouseEnter={e => e.currentTarget.style.background = '#fafaf9'}
               onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
              <PriorityPill priority={f.priority}/>
              <span style={{fontSize: 13, fontWeight: 600, color: '#080707', flex: 1}}>{f.title}</span>
              <span style={{fontSize: 11, color: '#706e6b'}}>Risk {f.riskScore}</span>
              <Icon d={ICONS.chevR} size={12} color="#706e6b"/>
            </div>
          ))}
        </div>
      </div>
    </Card>
  );
}

function LaneFlow({ lanes, onOpenFinding, findings, object }) {
  // Render lanes horizontally with connectors. Each lane is a column showing items.
  const kindMeta = {
    'before-flow': { color: '#7f8de1', label: 'Before Save Flow', icon: ICONS.flow },
    'trigger':     { color: '#a094ed', label: 'Apex Trigger',     icon: ICONS.apex },
    'after-flow':  { color: '#0070d2', label: 'After Save Flow',  icon: ICONS.flow },
    'workflow':    { color: '#dd7a01', label: 'Workflow Rule',    icon: ICONS.refresh },
    'process':     { color: '#c23934', label: 'Process Builder',  icon: ICONS.refresh },
  };

  const healthDot = (h) => h === 'error' ? '#c23934' : h === 'warn' ? '#dd7a01' : '#3ba755';

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
      {/* Trigger source */}
      <div style={{display: 'flex', alignItems: 'center', gap: 12}}>
        <div style={{
          padding: '10px 16px', background: '#032d60', color: '#fff',
          borderRadius: 4, fontSize: 13, fontWeight: 700,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <Icon d={ICONS.play} size={12}/>
          {object} record save
        </div>
        <div style={{flex: 1, height: 1, background: '#dddbda'}}/>
        <span style={{fontSize: 11, color: '#706e6b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em'}}>Order of execution →</span>
      </div>

      {/* Lane cards */}
      {lanes.map((lane, laneIdx) => {
        const meta = kindMeta[lane.kind];
        return (
          <div key={lane.label} style={{display: 'flex', gap: 12, alignItems: 'flex-start'}}>
            {/* Lane label column */}
            <div style={{width: 160, flexShrink: 0, paddingTop: 6}}>
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '4px 10px', borderRadius: 4,
                background: meta.color, color: '#fff',
                fontSize: 11, fontWeight: 700,
              }}>
                <Icon d={meta.icon} size={11}/>
                {lane.label}
              </div>
              <div style={{fontSize: 11, color: '#706e6b', marginTop: 6}}>{lane.items.length} active</div>
            </div>

            {/* Items row */}
            <div style={{flex: 1, display: 'flex', flexWrap: 'wrap', gap: 8}}>
              {lane.items.map((item, i) => (
                <div key={item.name} style={{
                  flex: '1 1 240px', maxWidth: 320, minWidth: 220,
                  padding: '10px 12px', background: '#fff',
                  border: `1px solid ${item.health === 'error' ? '#f6a9a5' : item.health === 'warn' ? '#fcb95b' : '#dddbda'}`,
                  borderLeft: `3px solid ${healthDot(item.health)}`,
                  borderRadius: 4, cursor: 'pointer',
                  transition: 'box-shadow 150ms, transform 150ms',
                }} onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.08)'; }}
                   onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; }}>
                  <div style={{display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4}}>
                    <span style={{width: 6, height: 6, borderRadius: '50%', background: healthDot(item.health), flexShrink: 0}}/>
                    <div style={{
                      fontSize: 12, fontWeight: 700, color: '#080707',
                      fontFamily: 'SFMono-Regular, Consolas, monospace',
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }} title={item.name}>{item.name}</div>
                  </div>
                  <div style={{display: 'flex', alignItems: 'center', gap: 8, marginTop: 4}}>
                    <span style={{fontSize: 10, color: '#706e6b'}}>Modified {item.lastModified}</span>
                    <span style={{fontSize: 10, color: '#706e6b'}}>· {item.runs7d.toLocaleString()} runs/7d</span>
                  </div>
                  {item.note && (
                    <div style={{
                      marginTop: 6, fontSize: 11, color: item.health === 'error' ? '#ba0517' : '#a96404',
                      fontWeight: 600,
                    }}>
                      <Icon d={ICONS.warn} size={10} style={{display:'inline-block', verticalAlign:'-1px', marginRight: 3}}/>
                      {item.note}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        );
      })}

      {/* Legend */}
      <div style={{
        marginTop: 8, padding: 10,
        background: '#fafaf9', border: '1px solid #ecebea',
        borderRadius: 4, display: 'flex', gap: 16, flexWrap: 'wrap',
        fontSize: 11, color: '#3e3e3c',
      }}>
        <span><span style={{display:'inline-block', width: 8, height: 8, background: '#3ba755', borderRadius: '50%', marginRight: 4, verticalAlign: 'middle'}}/>Healthy</span>
        <span><span style={{display:'inline-block', width: 8, height: 8, background: '#dd7a01', borderRadius: '50%', marginRight: 4, verticalAlign: 'middle'}}/>Warning — should migrate or refactor</span>
        <span><span style={{display:'inline-block', width: 8, height: 8, background: '#c23934', borderRadius: '50%', marginRight: 4, verticalAlign: 'middle'}}/>Error — fault path missing or EOL component</span>
      </div>
    </div>
  );
}

Object.assign(window, { AutomationMap });
