// DiagramBundleFlow.jsx — Diagram 1: end-to-end bundle builder flow.
// 4 swim lanes (Browser, Shopify Proxy, Worker, Recharge) running top-to-bottom.
// 7 steps, each rendered as a row with a numbered node in its lane and arrows
// crossing between lanes when the action spans them. Description sits to the right.

const LANES = [
  { id: 'browser', label: 'Browser (PDP)',      color: BRAND.swim1 },
  { id: 'proxy',   label: 'Shopify App Proxy',  color: BRAND.swim2 },
  { id: 'worker',  label: 'Cloudflare Worker',  color: BRAND.swim3 },
  { id: 'recharge',label: 'Recharge API',       color: BRAND.swim4 },
];

// Each step: from / to lane index (or single lane), description.
// `from`/`to` are lane indexes (0-3). If equal, it's an in-lane action (no arrow).
// `dir` is 'right' or 'left' — affects arrow direction.
const STEPS = [
  { n: 1, from: 0, to: 0, dir: 'right',
    head: 'Shopper picks items + cadence',
    body: 'On the PDP, the shopper selects bundle contents and a subscription cadence.' },
  { n: 2, from: 0, to: 1, dir: 'right',
    head: 'POST /apps/recharge/bundles/selection',
    body: 'Browser hits the App Proxy. Shopify signs the request HMAC.' },
  { n: 3, from: 1, to: 2, dir: 'right',
    head: 'Proxy forwards to Worker',
    body: 'HMAC verified; request handed to the Cloudflare Worker.' },
  { n: 4, from: 2, to: 3, dir: 'right',
    head: 'Worker creates selection',
    body: 'Server-to-server call to Recharge using the secret API key, never exposed to the browser.' },
  { n: 5, from: 3, to: 0, dir: 'left',
    head: 'selection_id returned',
    body: 'Recharge returns the selection id; Worker passes it back through the proxy to the browser.' },
  { n: 6, from: 0, to: 0, dir: 'right',
    head: 'Add to cart with line-item properties',
    body: <>Browser adds the item with <Code>_recharge_bundle_selection_id</Code> and <Code>selling_plan</Code> from the metafield mirror.</> },
  { n: 7, from: 0, to: 3, dir: 'right', wide: true,
    head: 'Checkout → webhook → subscription',
    body: 'Shopify Checkout completes the order. Recharge sees the line-item property via webhook, creates the subscription with the bundle contents.' },
];

const BundleFlow = () => {
  // Layout constants
  const LANE_W = 170;            // px per lane
  const LANE_GAP = 20;
  const ROW_H = 96;
  // HEADER_H = combined height of lane-label text (~16) + 6 gap + 3 bar + 16 marginBottom
  const HEADER_H = 25;
  const NODE_R = 18;
  const DESC_W = 360;
  const LANES_TOTAL = LANES.length * LANE_W + (LANES.length - 1) * LANE_GAP;

  return (
    <div style={{
      padding: '56px 48px 64px', maxWidth: 1280, margin: '0 auto',
    }}>
      <FigureHeader
        kicker="Figure 01 — Bundle Builder Flow"
        title="How a bundle becomes a subscription."
        subtitle="A 7-step flow that touches four systems but introduces only one new piece of infrastructure on Platter's side: a small Cloudflare Worker that holds the Recharge API key."
      />

      <div style={{
        display: 'grid',
        gridTemplateColumns: `${LANES_TOTAL}px ${DESC_W}px`,
        gap: 40, marginTop: 48,
        position: 'relative',
      }}>
        {/* === Left: swim lane visual === */}
        <div style={{ position: 'relative', minHeight: HEADER_H + STEPS.length * ROW_H }}>
          {/* Lane headers */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: `repeat(${LANES.length}, ${LANE_W}px)`,
            gap: LANE_GAP, marginBottom: 16,
          }}>
            {LANES.map(L => (
              <div key={L.id} style={{ textAlign: 'center' }}>
                <div style={{
                  fontFamily: BRAND.sans, fontSize: 13, fontWeight: 600,
                  color: BRAND.fg, marginBottom: 6, lineHeight: 1.2,
                }}>{L.label}</div>
                <div style={{
                  height: 3, background: L.color, opacity: 0.9,
                }}/>
              </div>
            ))}
          </div>

          {/* Lane rails */}
          <div style={{ position: 'relative', minHeight: STEPS.length * ROW_H + 20 }}>
            <svg
              width="100%"
              height={STEPS.length * ROW_H + 20}
              viewBox={`0 0 ${LANES_TOTAL} ${STEPS.length * ROW_H + 20}`}
              style={{ display: 'block' }}
              role="img"
              aria-label="Bundle builder flow diagram. Seven steps traversing four systems: the browser, Shopify App Proxy, Cloudflare Worker, and Recharge API."
            >
              <defs>
                {LANES.map((L, i) => (
                  <marker key={'a' + i} id={`arr-${i}`} viewBox="0 0 10 10"
                    refX="8" refY="5" markerWidth="9" markerHeight="9" orient="auto-start-reverse">
                    <path d="M0 0 L10 5 L0 10 z" fill={L.color}/>
                  </marker>
                ))}
              </defs>

              {/* Vertical rails for each lane */}
              {LANES.map((L, i) => {
                const x = i * (LANE_W + LANE_GAP) + LANE_W / 2;
                return (
                  <line key={L.id} x1={x} y1={0} x2={x} y2={STEPS.length * ROW_H + 10}
                    stroke={L.color} strokeOpacity="0.18" strokeWidth="1.5"
                    strokeDasharray="3 5"/>
                );
              })}

              {/* Step lines + nodes */}
              {STEPS.map((s, idx) => {
                const y = idx * ROW_H + ROW_H / 2;
                const xFrom = s.from * (LANE_W + LANE_GAP) + LANE_W / 2;
                const xTo = s.to * (LANE_W + LANE_GAP) + LANE_W / 2;
                const color = LANES[s.from].color;
                const toColor = LANES[s.to].color;
                const sameLane = s.from === s.to;

                return (
                  <g key={s.n}>
                    {/* Connecting line between lanes */}
                    {!sameLane && (
                      <line
                        x1={s.dir === 'right' ? xFrom + NODE_R : xFrom - NODE_R}
                        y1={y}
                        x2={s.dir === 'right' ? xTo - NODE_R : xTo + NODE_R}
                        y2={y}
                        stroke={s.dir === 'right' ? toColor : color}
                        strokeWidth="1.8"
                        markerEnd={`url(#arr-${s.dir === 'right' ? s.to : s.from})`}
                      />
                    )}
                    {/* "From" node — filled */}
                    <circle cx={xFrom} cy={y} r={NODE_R} fill={color}/>
                    <text x={xFrom} y={y + 4} textAnchor="middle"
                      fontFamily={BRAND.mono} fontSize="13" fontWeight="700"
                      fill={BRAND.cream}>{s.n}</text>
                    {/* "To" node — ring */}
                    {!sameLane && (
                      <circle cx={xTo} cy={y} r={NODE_R - 1}
                        fill={BRAND.paper} stroke={toColor} strokeWidth="1.8"/>
                    )}
                  </g>
                );
              })}
            </svg>
          </div>
        </div>

        {/* === Right: step descriptions === */}
        <div style={{
          display: 'flex', flexDirection: 'column',
          paddingTop: HEADER_H + 16, gap: 0,
        }}>
          {STEPS.map((s, idx) => (
            <div key={s.n} style={{
              minHeight: ROW_H,
              padding: '4px 0',
              display: 'flex', flexDirection: 'column', justifyContent: 'center',
              borderTop: idx === 0 ? `1px solid ${BRAND.line}` : 'none',
              borderBottom: `1px solid ${BRAND.line}`,
            }}>
              <div style={{
                fontFamily: BRAND.sans, fontSize: 14, fontWeight: 600,
                color: BRAND.fg, marginBottom: 4, lineHeight: 1.3,
              }}>{s.head}</div>
              <div style={{
                fontFamily: BRAND.sans, fontSize: 13, lineHeight: 1.5,
                color: BRAND.fgSoft, textWrap: 'pretty',
              }}>{s.body}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Caption / takeaway */}
      <div style={{
        marginTop: 36, padding: '20px 24px',
        background: BRAND.bgSoft, border: `1px solid ${BRAND.line}`,
        borderLeft: `2px solid ${BRAND.forest}`,
        fontFamily: BRAND.sans, fontSize: 14.5, lineHeight: 1.55,
        color: BRAND.fgSoft,
      }}>
        <span style={{
          fontFamily: BRAND.mono, fontSize: 10.5, letterSpacing: 1.2,
          textTransform: 'uppercase', color: BRAND.forest, fontWeight: 600,
          marginRight: 10,
        }}>The point</span>
        Everything else — managing subscriptions, billing, charges, payment updates — stays in the Recharge Unity portal. The custom app owns one job: holding the API key so the bundle builder can talk to Recharge from the browser without exposing the secret.
      </div>
    </div>
  );
};

// Shared figure header (reused by the other diagrams)
const FigureHeader = ({ kicker, title, subtitle }) => (
  <div style={{ maxWidth: 760 }}>
    <div style={{
      fontFamily: BRAND.mono, fontSize: 12, letterSpacing: 1.4,
      textTransform: 'uppercase', color: BRAND.fgMuted, marginBottom: 14,
    }}>{kicker}</div>
    <h3 style={{
      fontFamily: BRAND.serif, fontWeight: 400, fontSize: 42,
      lineHeight: 1.05, letterSpacing: -1.2, margin: 0, textWrap: 'balance',
    }}>{title}</h3>
    {subtitle && (
      <p style={{
        fontFamily: BRAND.sans, fontSize: 17, lineHeight: 1.5,
        color: BRAND.fgSoft, margin: '14px 0 0', textWrap: 'pretty', maxWidth: 720,
      }}>{subtitle}</p>
    )}
  </div>
);

Object.assign(window, { BundleFlow, FigureHeader });
