// flow.jsx — Animated "inputs → pipeline → outputs" platform graphic.
// One self-contained SVG (foreignObject cards) so labels, connectors, and the
// pipeline always stay aligned and scale together. Used on Home and Solutions.

const FLOW_INPUTS = [
  'Clinical Notes',
  'Provider & Clinical Rationale',
  'Payer Policy Intelligence',
  'Procedure & Coding',
  'Claims & Denials'
];

const FLOW_STAGES = [
  { name: 'Ingest',    desc: 'Notes read in real time as the physician writes.', pattern: 'incoming' },
  { name: 'Detect',    desc: 'Procedure, payer, and policy identified at once.', pattern: 'focus' },
  { name: 'Map',       desc: 'Every medical-necessity criterion matched line by line.', pattern: 'grid' },
  { name: 'Assemble',  desc: 'The authorization packet builds itself from the chart.', pattern: 'block' },
  { name: 'Reconcile', desc: 'Claims, denials, and appeals closed against the policy.', pattern: 'converge' }
];

const FLOW_OUTPUTS = [
  { name: 'Cleaner authorizations', sub: 'Approved on the first submission' },
  { name: 'Recovered revenue',      sub: 'Denials caught before they leak' },
  { name: 'Time back to physicians',sub: 'Hours of rework removed' },
  { name: 'Audit-ready trail',      sub: 'Every decision traced to the chart' }
];

// 5×5 dot patterns for the stage icons
const FLOW_PATTERNS = {
  incoming: '10000 11000 11100 11000 10000',
  focus:    '00000 01110 01110 01110 00000',
  grid:     '10101 01010 10101 01010 10101',
  block:    '01110 01110 01110 01110 00000',
  converge: '10001 01010 00100 01010 10001'
};

function FlowDotIcon({ pattern, active }) {
  const rows = (FLOW_PATTERNS[pattern] || FLOW_PATTERNS.grid).split(' ');
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 3,
      width: 44, height: 44
    }}>
      {rows.flatMap((r, ri) => r.split('').map((c, ci) => (
        <span key={ri + '-' + ci} style={{
          width: 5, height: 5, borderRadius: 999,
          background: c === '1'
            ? (active ? '#7CF0B4' : '#5FD39A')
            : 'rgba(255,255,255,0.14)',
          transition: 'background .4s ease',
          boxShadow: c === '1' && active ? '0 0 6px rgba(124,240,180,0.7)' : 'none'
        }} />
      )))}
    </div>
  );
}

function PlatformFlow({ title, subtitle, eyebrow }) {
  const [active, setActive] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setActive(a => (a + 1) % FLOW_STAGES.length), 1600);
    return () => clearInterval(t);
  }, []);

  // Geometry (viewBox coordinates)
  const VB_W = 1600, VB_H = 480;
  const inputYs = [115, 190, 265, 340, 415];
  const outputYs = [140, 223, 306, 389];
  const busL = 300, busR = 1300;
  const cardX0 = 375, cardGap = 14, cardN = 5;
  const cardRight = 1225;
  const cardW = (cardRight - cardX0 - cardGap * (cardN - 1)) / cardN; // ~158.8
  const cardY = 120, cardH = 290;
  const midY = 265;

  const inPath = (y) => `M205,${y} L${busL},${y} L${busL},${midY} L${cardX0},${midY}`;
  const outPath = (y) => `M${cardRight},${midY} L${busR},${midY} L${busR},${y} L1375,${y}`;

  return (
    <section className="section section-divider band-emerald emerald-field">
      <div className="cmd-container">
        <div style={{ marginBottom: 36 }}>
          <div className="eyebrow" style={{ marginBottom: 12, color: '#5FD39A' }}>
            {eyebrow || 'How we work'}
          </div>
          <h2 className="h-1" style={{
            fontSize: 'clamp(28px, 3.4vw, 44px)', margin: 0, color: '#fff', lineHeight: 1.08
          }}>
            {title || <>From every input to{' '}<span style={{ color: '#5FD39A' }}>one clean outcome.</span></>}
          </h2>
          <p className="lede" style={{ marginTop: 18, fontSize: 18.5, color: 'rgba(255,255,255,0.78)', maxWidth: 'none' }}>
            {subtitle || 'CriterionMD unifies clinical documentation, provider rationale, and payer intelligence, then turns it into authorizations that actually get paid.'}
          </p>
        </div>

        <div style={{ overflowX: 'auto', overflowY: 'hidden', paddingBottom: 4 }}>
          <svg viewBox={`0 0 ${VB_W} ${VB_H}`} width="100%"
               style={{ minWidth: 960, maxWidth: 1240, display: 'block', margin: '0 auto' }}
               role="img" aria-label="CriterionMD platform data flow">
            <defs>
              <marker id="flowArrow" markerWidth="9" markerHeight="9" refX="6" refY="4.5"
                      orient="auto" markerUnits="userSpaceOnUse">
                <path d="M1,1 L7,4.5 L1,8" fill="none" stroke="#5FD39A" strokeWidth="1.4"
                      strokeLinecap="round" strokeLinejoin="round" />
              </marker>
            </defs>

            {/* Section headers */}
            <text x="100" y="74" textAnchor="middle" fill="rgba(255,255,255,0.5)"
                  style={{ font: "500 13px var(--font-mono)", letterSpacing: '.14em' }}>INPUTS</text>
            <text x={cardX0 + (cardRight - cardX0) / 2} y="74" textAnchor="middle" fill="rgba(255,255,255,0.5)"
                  style={{ font: "500 13px var(--font-mono)", letterSpacing: '.14em' }}>THE PLATFORM</text>
            <text x="1488" y="74" textAnchor="middle" fill="rgba(255,255,255,0.5)"
                  style={{ font: "500 13px var(--font-mono)", letterSpacing: '.14em' }}>OUTCOMES</text>

            {/* Connectors — inputs */}
            {inputYs.map((y, i) => (
              <g key={'in' + i}>
                <path d={inPath(y)} fill="none" stroke="rgba(255,255,255,0.16)" strokeWidth="1.5"
                      markerEnd={i === 2 ? 'url(#flowArrow)' : undefined} />
                <circle r="3.2" fill="#5FD39A">
                  <animateMotion dur="2.4s" repeatCount="indefinite" begin={`${i * 0.32}s`}
                                 path={inPath(y)} />
                  <animate attributeName="opacity" dur="2.4s" repeatCount="indefinite"
                           begin={`${i * 0.32}s`} values="0;1;1;0.2" keyTimes="0;0.15;0.8;1" />
                </circle>
              </g>
            ))}

            {/* Connectors — outputs */}
            {outputYs.map((y, j) => (
              <g key={'out' + j}>
                <path d={outPath(y)} fill="none" stroke="rgba(255,255,255,0.16)" strokeWidth="1.5"
                      markerEnd="url(#flowArrow)" />
                <circle r="3.2" fill="#5FD39A">
                  <animateMotion dur="2.4s" repeatCount="indefinite" begin={`${0.6 + j * 0.3}s`}
                                 path={outPath(y)} />
                  <animate attributeName="opacity" dur="2.4s" repeatCount="indefinite"
                           begin={`${0.6 + j * 0.3}s`} values="0;1;1;0.2" keyTimes="0;0.15;0.8;1" />
                </circle>
              </g>
            ))}

            {/* Input labels */}
            {FLOW_INPUTS.map((label, i) => (
              <foreignObject key={label} x="0" y={inputYs[i] - 26} width="200" height="52">
                <div style={{
                  height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
                  textAlign: 'right', fontSize: 14.5, fontWeight: 500, lineHeight: 1.2,
                  color: 'rgba(255,255,255,0.86)', letterSpacing: '-0.005em', paddingRight: 4
                }}>{label}</div>
              </foreignObject>
            ))}

            {/* Pipeline cards */}
            {FLOW_STAGES.map((s, i) => {
              const x = cardX0 + i * (cardW + cardGap);
              const on = active === i;
              return (
                <foreignObject key={s.name} x={x} y={cardY} width={cardW} height={cardH}>
                  <div style={{
                    height: '100%', boxSizing: 'border-box',
                    borderRadius: 16, padding: '22px 18px',
                    border: '1px solid ' + (on ? 'rgba(124,240,180,0.7)' : 'rgba(255,255,255,0.12)'),
                    background: on ? 'rgba(124,240,180,0.08)' : 'rgba(255,255,255,0.04)',
                    boxShadow: on ? '0 0 0 1px rgba(124,240,180,0.3), 0 18px 50px -24px rgba(124,240,180,0.5)' : 'none',
                    display: 'flex', flexDirection: 'column', gap: 12,
                    transition: 'all .45s cubic-bezier(.2,.7,.2,1)'
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                      <FlowDotIcon pattern={s.pattern} active={on} />
                      <span style={{
                        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.12em',
                        color: on ? '#7CF0B4' : 'rgba(255,255,255,0.4)', transition: 'color .4s'
                      }}>{String(i + 1).padStart(2, '0')}</span>
                    </div>
                    <div style={{
                      fontSize: 18, fontWeight: 600, color: '#fff', letterSpacing: '-0.01em'
                    }}>{s.name}</div>
                    <div style={{
                      fontSize: 13, lineHeight: 1.45, color: 'rgba(255,255,255,0.72)'
                    }}>{s.desc}</div>
                  </div>
                </foreignObject>
              );
            })}

            {/* Output labels */}
            {FLOW_OUTPUTS.map((o, j) => (
              <foreignObject key={o.name} x="1385" y={outputYs[j] - 30} width="215" height="60">
                <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', height: '100%' }}>
                  <div style={{ fontSize: 15.5, fontWeight: 600, color: '#fff', letterSpacing: '-0.01em', lineHeight: 1.2 }}>{o.name}</div>
                  <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.6)', marginTop: 3, lineHeight: 1.3 }}>{o.sub}</div>
                </div>
              </foreignObject>
            ))}
          </svg>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { PlatformFlow });
