/* global React */

// ============================================================
// WE DELIVER — Secure · Scalable · Intelligent Advisory Platform
// 10 capabilities orbiting a central BEL device with animated ring
// ============================================================
const WeDeliver = () => {
  const left = [
    { n: "01", t: "Auto Scaling & Agility", icon: "scaling" },
    { n: "02", t: "High Availability & Reliability", icon: "availability" },
    { n: "03", t: "Pay-As-You-Go Pricing", icon: "pricing" },
    { n: "04", t: "Managed Databases", icon: "database" },
    { n: "05", t: "Backup & Disaster Recovery", icon: "backup" },
  ];
  const right = [
    { n: "06", t: "Multi-Layer Security & Governance", icon: "lock" },
    { n: "07", t: "AI & Machine Learning", icon: "brain" },
    { n: "08", t: "Multi-Factor Authentication (MFA)", icon: "fingerprint" },
    { n: "09", t: "Single Sign-On (SSO)", icon: "sso" },
    { n: "10", t: "Monitoring & Automation", icon: "monitor" },
  ];

  // Refs for dynamic connector measurement
  const hubRef = React.useRef(null);
  const leftRefs = React.useRef([]);
  const rightRefs = React.useRef([]);
  const deviceRef = React.useRef(null);
  const screenRef = React.useRef(null);
  const [paths, setPaths] = React.useState([]);
  const [box, setBox] = React.useState({ w: 1200, h: 580 });

  React.useLayoutEffect(() => {
    const compute = () => {
      const hub = hubRef.current;
      const dev = deviceRef.current;
      const scr = screenRef.current;
      if (!hub || !dev) return;
      const hb = hub.getBoundingClientRect();
      const db = dev.getBoundingClientRect();
      // Use the screen rect for the vertical range so all entry points stay
      // inside the opaque screen panel (with a small inset). Falls back to
      // the device rect if the screen ref hasn't mounted yet.
      const sb = scr ? scr.getBoundingClientRect() : db;
      setBox({ w: hb.width, h: hb.height });

      const newPaths = [];
      // Per-index ratios within the screen panel (avoid 0.5 for middle pill
      // so its connector curls instead of going flat behind the ring band).
      const ratios = [0.20, 0.36, 0.54, 0.66, 0.80];
      leftRefs.current.forEach((el, i) => {
        if (!el) return;
        const r = el.getBoundingClientRect();
        const sx = r.right - hb.left;
        const sy = r.top + r.height / 2 - hb.top;
        const ratio = ratios[i] ?? 0.5;
        // Push endpoint well inside the laptop SCREEN so the dot + pulse
        // halo are fully hidden behind the screen panel.
        const ex = sb.left - hb.left + 16;
        const ey = sb.top - hb.top + sb.height * ratio;
        newPaths.push({ side: "L", sx, sy, ex, ey, i });
      });
      rightRefs.current.forEach((el, i) => {
        if (!el) return;
        const r = el.getBoundingClientRect();
        const sx = r.left - hb.left;
        const sy = r.top + r.height / 2 - hb.top;
        const ratio = ratios[i] ?? 0.5;
        const ex = sb.right - hb.left - 16;
        const ey = sb.top - hb.top + sb.height * ratio;
        newPaths.push({ side: "R", sx, sy, ex, ey, i });
      });
      setPaths(newPaths);
    };
    compute();
    const ro = new ResizeObserver(compute);
    if (hubRef.current) ro.observe(hubRef.current);
    window.addEventListener("resize", compute);
    return () => { ro.disconnect(); window.removeEventListener("resize", compute); };
  }, []);

  return (
    <section style={{ background: "var(--cream)", position: "relative", overflow: "hidden", paddingBlock: "clamp(48px, 5vw, 88px)" }}>
      <div aria-hidden style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(circle at 50% 50%, rgba(120,69,233,0.08), transparent 60%)",
      }} />
      <div className="wrap" style={{ position: "relative", display: "flex", flexDirection: "column", gap: 28 }}>
        {/* Eyebrow row — three dot pills */}
        <div className="reveal" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 32, flexWrap: "wrap" }}>
          {[
            { l: "Secure", c: "var(--bel-orange)" },
            { l: "Scalable", c: "var(--bel-blue)" },
            { l: "Intelligent Advisory", c: "#16A34A" },
          ].map((p, i) => (
            <span key={i} style={{
              display: "inline-flex", alignItems: "center", gap: 10,
              fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 500,
              color: "var(--ink)", letterSpacing: "-0.01em",
            }}>
              <span style={{ width: 10, height: 10, borderRadius: "50%", background: p.c, boxShadow: `0 0 0 4px ${p.c}22` }} />
              {p.l}
            </span>
          ))}
        </div>

        {/* Main hub */}
        <div className="wd-hub" ref={hubRef}>
          {/* Dynamic SVG connectors */}
          <svg aria-hidden width={box.w} height={box.h} viewBox={`0 0 ${box.w} ${box.h}`} className="wd-lines">
            <defs>
              <linearGradient id="wdLineL" x1="0" x2="1" y1="0" y2="0">
                <stop offset="0%" stopColor="var(--bel-orange)" stopOpacity="0.9"/>
                <stop offset="100%" stopColor="var(--bel-orange)" stopOpacity="0.35"/>
              </linearGradient>
              <linearGradient id="wdLineR" x1="1" x2="0" y1="0" y2="0">
                <stop offset="0%" stopColor="var(--bel-blue)" stopOpacity="0.9"/>
                <stop offset="100%" stopColor="var(--bel-blue)" stopOpacity="0.35"/>
              </linearGradient>
            </defs>

            {paths.map((p, idx) => {
              const isL = p.side === "L";
              // Smooth S-curve: horizontal flat near start, then curve to entry
              const cx1 = isL ? p.sx + (p.ex - p.sx) * 0.55 : p.sx - (p.sx - p.ex) * 0.55;
              const cx2 = isL ? p.ex - 8 : p.ex + 8;
              const d = `M ${p.sx} ${p.sy} C ${cx1} ${p.sy}, ${cx2} ${p.ey}, ${p.ex} ${p.ey}`;
              const color = isL ? "var(--bel-orange)" : "var(--bel-blue)";
              const gradId = isL ? "url(#wdLineL)" : "url(#wdLineR)";
              return (
                <g key={`${p.side}${p.i}`}>
                  <path d={d} stroke={gradId} strokeWidth="1.5" strokeDasharray="4 5" fill="none" strokeLinecap="round"
                        className={`wd-line ${isL ? "wd-line-left" : "wd-line-right"}`}
                        style={{ animationDelay: `${p.i * 0.18}s` }} />
                  {/* Endpoint at device */}
                  <circle cx={p.ex} cy={p.ey} r="3" fill={color} className="wd-node"
                          style={{ animationDelay: `${p.i * 0.3}s` }} />
                  <circle cx={p.ex} cy={p.ey} r="8" fill={color} opacity="0.25" className="wd-node-pulse"
                          style={{ animationDelay: `${p.i * 0.3}s`, transformOrigin: `${p.ex}px ${p.ey}px` }} />
                  {/* Endpoint at pill */}
                  <circle cx={p.sx} cy={p.sy} r="2.5" fill={color}/>
                </g>
              );
            })}
          </svg>

          <div className="wd-col wd-col-left">
            {left.map((it, i) => (
              <FeaturePill key={i} {...it} side="left" delay={i * 0.08}
                pillRef={el => leftRefs.current[i] = el} />
            ))}
          </div>

          <CenterDevice deviceRef={deviceRef} screenRef={screenRef} />

          <div className="wd-col wd-col-right">
            {right.map((it, i) => (
              <FeaturePill key={i} {...it} side="right" delay={0.4 + i * 0.08}
                pillRef={el => rightRefs.current[i] = el} />
            ))}
          </div>
        </div>
      </div>

      <style>{`
        .wd-hub {
          position: relative;
          display: grid;
          grid-template-columns: 1fr 480px 1fr;
          align-items: center;
          gap: 32px;
          min-height: 600px;
        }
        .wd-lines {
          position: absolute; inset: 0;
          pointer-events: none;
          overflow: visible;
          z-index: 1;
        }
        .wd-col { position: relative; z-index: 2; display: flex; flex-direction: column; gap: 18px; }
        .wd-col-left { align-items: flex-start; padding-right: 8px; }
        .wd-col-right { align-items: flex-end; padding-left: 8px; }

        .wd-line {
          stroke-dasharray: 4 5;
          animation: wdDashOut 1.6s linear infinite;
        }
        .wd-line-right { animation-name: wdDashOut; }
        @keyframes wdDashOut {
          from { stroke-dashoffset: 0; }
          to   { stroke-dashoffset: 18; }
        }
        .wd-node { animation: wdNodeBlink 2.2s ease-in-out infinite; }
        .wd-node-pulse {
          animation: wdNodeRipple 2.2s ease-out infinite;
        }
        @keyframes wdNodeBlink {
          0%, 100% { opacity: 1; }
          50%      { opacity: 0.55; }
        }
        @keyframes wdNodeRipple {
          0%   { transform: scale(0.5); opacity: 0.45; }
          70%  { transform: scale(2.2); opacity: 0; }
          100% { transform: scale(2.2); opacity: 0; }
        }

        @media (max-width: 980px) {
          .wd-hub { grid-template-columns: 1fr; min-height: 0; }
          .wd-lines { display: none; }
          .wd-col-left, .wd-col-right { align-items: stretch; padding: 0; }
        }
      `}</style>
    </section>
  );
};

// Individual feature pill
const FeaturePill = ({ n, t, icon, side, delay, pillRef }) => {
  const numFirst = side === "left";
  return (
    <article ref={pillRef} className="wd-pill reveal" style={{
      display: "flex", alignItems: "center", gap: 14,
      flexDirection: numFirst ? "row" : "row-reverse",
      transitionDelay: `${delay}s`,
    }}>
      {/* Icon circle */}
      <span style={{
        width: 48, height: 48, borderRadius: "50%",
        background: "var(--bel-blue-soft)",
        color: "var(--bel-blue-deep)",
        display: "grid", placeItems: "center",
        flexShrink: 0,
        border: "1px solid color-mix(in oklab, var(--bel-blue) 25%, transparent)",
        boxShadow: "0 8px 18px -10px rgba(120,69,233,0.45)",
      }}>
        <PillIcon kind={icon} />
      </span>

      {/* Label pill */}
      <span style={{
        display: "inline-flex", alignItems: "center", gap: 12,
        flexDirection: numFirst ? "row" : "row-reverse",
        padding: "10px 14px 10px 14px",
        background: "var(--paper)",
        border: "1px solid var(--line)",
        borderRadius: 999,
        boxShadow: "0 12px 24px -18px rgba(24,24,27,0.18)",
        fontWeight: 600, fontSize: 14.5, color: "var(--ink-2)",
        letterSpacing: "-0.005em",
        whiteSpace: "nowrap",
      }}>
        {numFirst ? <>{t}<NumBadge n={n} /></> : <><NumBadge n={n} />{t}</>}
      </span>
    </article>
  );
};

const NumBadge = ({ n }) => (
  <span style={{
    width: 30, height: 30, borderRadius: "50%",
    background: "var(--bel-blue-deep)",
    color: "white",
    fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 700,
    letterSpacing: "0.04em",
    display: "grid", placeItems: "center",
    flexShrink: 0,
    boxShadow: "0 6px 14px -6px rgba(85,35,189,0.6)",
  }}>{n}</span>
);

// ============================================================
// Center device — laptop with BEL emblem on screen + gradient ring
// ============================================================
const CenterDevice = ({ deviceRef, screenRef }) => (
  <div className="wd-center reveal" style={{
    position: "relative",
    aspectRatio: "1 / 1",
    display: "grid", placeItems: "center",
    zIndex: 2,
  }}>
    {/* Outer animated ring */}
    <div className="wd-ring" />
    {/* Inner subtle ring */}
    <div className="wd-ring-inner" />

    {/* Orbit dots */}
    {[0, 72, 144, 216, 288].map((deg, i) => (
      <span key={i} className="wd-orbit-dot" style={{ "--deg": `${deg}deg`, animationDelay: `${i * 0.4}s` }} />
    ))}

    {/* Laptop body */}
    <div ref={deviceRef} style={{
      position: "relative",
      width: "48%", aspectRatio: "1.45 / 1",
      display: "flex", flexDirection: "column", alignItems: "center",
      filter: "drop-shadow(0 24px 36px rgba(85,35,189,0.22))",
      animation: "wdFloat 6s ease-in-out infinite",
    }}>
      {/* Screen */}
      <div ref={screenRef} style={{
        width: "100%", aspectRatio: "1.55 / 1",
        background: "var(--paper)",
        border: "3px solid var(--ink)",
        borderRadius: "10px 10px 4px 4px",
        padding: 10,
        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
        gap: 6,
        position: "relative",
        overflow: "hidden",
      }}>
        {/* Subtle inner gradient bg */}
        <div aria-hidden style={{
          position: "absolute", inset: 0,
          background: "radial-gradient(ellipse at 50% 40%, rgba(239,106,31,0.08), transparent 60%)",
        }} />
        {/* XSOL CLOUD emblem (brand mark) */}
        <div style={{ position: "relative", display: "grid", placeItems: "center" }}>
          <XsolCloudMark size={190} color="var(--bel-orange)" strokeWidth={6} />
        </div>
      </div>
      {/* Base */}
      <div style={{
        width: "108%", height: 9,
        background: "linear-gradient(180deg, var(--ink) 0%, #2A2A2F 100%)",
        borderRadius: "0 0 8px 8px",
        marginTop: -2,
        boxShadow: "0 6px 12px -6px rgba(0,0,0,0.4)",
      }} />
      <div style={{
        width: 54, height: 4,
        background: "var(--ink)",
        borderRadius: "0 0 6px 6px",
      }} />

      {/* Platform label below */}
      <div style={{
        marginTop: 12,
        padding: "6px 16px",
        background: "var(--ink)",
        color: "var(--cream)",
        borderRadius: 999,
        fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", fontWeight: 600,
        textTransform: "uppercase",
      }}>Cloud Platform</div>
    </div>

    <style>{`
      .wd-center { width: 100%; max-width: 480px; margin: 0 auto; }
      .wd-ring {
        position: absolute; inset: 0;
        border-radius: 50%;
        background: conic-gradient(from 0deg, var(--bel-orange), #F0A04C, var(--bel-blue), var(--bel-blue-deep), var(--bel-orange));
        -webkit-mask: radial-gradient(circle, transparent 47%, #000 49%, #000 50%, transparent 51.5%);
                mask: radial-gradient(circle, transparent 47%, #000 49%, #000 50%, transparent 51.5%);
        animation: wdRotate 22s linear infinite;
      }
      .wd-ring-inner {
        position: absolute; inset: 8%;
        border-radius: 50%;
        border: 1.5px dashed rgba(120,69,233,0.45);
        animation: wdRingDance 18s linear infinite;
      }
      @keyframes wdRingDance {
        from { transform: rotate(0deg); }
        to   { transform: rotate(-360deg); }
      }
      .wd-orbit-dot {
        position: absolute; top: 50%; left: 50%;
        width: 12px; height: 12px; margin: -6px;
        border-radius: 50%;
        background: var(--bel-orange);
        box-shadow: 0 0 0 4px rgba(239,106,31,0.2), 0 4px 10px rgba(239,106,31,0.35);
        transform: rotate(var(--deg)) translateY(calc(-50% + 2px)) translateY(-46%);
        transform-origin: center;
        animation: wdDotPulse 2.6s ease-in-out infinite;
      }
      .wd-orbit-dot:nth-child(2) { background: var(--bel-blue); box-shadow: 0 0 0 4px rgba(120,69,233,0.2), 0 4px 10px rgba(120,69,233,0.35); }
      .wd-orbit-dot:nth-child(4) { background: var(--bel-blue); box-shadow: 0 0 0 4px rgba(120,69,233,0.2), 0 4px 10px rgba(120,69,233,0.35); }
      @keyframes wdRotate {
        from { transform: rotate(0deg); }
        to   { transform: rotate(360deg); }
      }
      @keyframes wdDotPulse {
        0%, 100% { box-shadow: 0 0 0 4px rgba(239,106,31,0.18), 0 4px 10px rgba(239,106,31,0.35); }
        50%      { box-shadow: 0 0 0 9px rgba(239,106,31,0), 0 4px 10px rgba(239,106,31,0.35); }
      }
      @keyframes wdFloat {
        0%, 100% { transform: translateY(0); }
        50%      { transform: translateY(-6px); }
      }
    `}</style>
  </div>
);

// Icon set for the pills
const PillIcon = ({ kind }) => {
  const p = { width: 20, height: 20, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (kind) {
    case "scaling":      return <svg {...p}><path d="M4 14v6h6M20 10V4h-6"/><path d="M20 4l-8 8M4 20l8-8"/></svg>;
    case "availability": return <svg {...p}><path d="M12 3l8 3v6c0 5-4 9-8 10-4-1-8-5-8-10V6l8-3z"/><path d="M8 13l3 3 5-6"/></svg>;
    case "pricing":      return <svg {...p}><circle cx="12" cy="12" r="9"/><path d="M14.5 9.5a3 3 0 0 0-5 0c0 3 5 1.5 5 4.5a3 3 0 0 1-5 0"/><path d="M12 7v1.5M12 15.5V17"/></svg>;
    case "database":     return <svg {...p}><ellipse cx="12" cy="5" rx="8" ry="2.5"/><path d="M4 5v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5V5"/><path d="M4 11v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5v-6"/></svg>;
    case "backup":       return <svg {...p}><path d="M7 17a5 5 0 0 1-1-9.7A6 6 0 0 1 17.7 8a4.5 4.5 0 0 1-.7 8.9H7z"/><path d="M12 12v6M9.5 15.5L12 18l2.5-2.5"/></svg>;
    case "lock":         return <svg {...p}><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>;
    case "brain":        return <svg {...p}><rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 9h6v6H9z"/><path d="M12 2v4M12 18v4M2 12h4M18 12h4M4 4l2 2M18 18l2 2M4 20l2-2M18 6l2-2"/></svg>;
    case "fingerprint":  return <svg {...p}><path d="M6 11a6 6 0 0 1 12 0v2"/><path d="M9 11a3 3 0 0 1 6 0v2c0 2 .5 4 1.5 5.5"/><path d="M12 11v4c0 1.5.5 3 1 4"/><path d="M7.5 17c.7 1.2 1 2.4 1 4M5 14c0-1 .2-2 .5-3"/></svg>;
    case "sso":          return <svg {...p}><circle cx="9" cy="9" r="3.5"/><path d="M3 20a6 6 0 0 1 12 0"/><path d="M15 11l3-3M18 8h2.5M18 8v2.5"/><circle cx="17" cy="16" r="1.5"/><path d="M17 17.5V20"/></svg>;
    case "monitor":      return <svg {...p}><rect x="3" y="4" width="18" height="13" rx="1.5"/><path d="M8 21h8M12 17v4"/><path d="M7 12l3-3 2 2 4-4"/></svg>;
    default: return null;
  }
};

Object.assign(window, { WeDeliver });
