// Services — BENTO LAYOUT with featured live-chat preview + 4 asymmetric cards.
// Breaks the "three cards in a row" rhythm. Each card has its own micro-visual.

function Services() {
  return (
    <section id="services" data-screen-label="02 Services" className="section">
      <div className="container">
        <div className="reveal" style={{
          display: "flex", justifyContent: "space-between", alignItems: "flex-end",
          gap: 24, marginBottom: 40, flexWrap: "wrap",
        }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <span className="eyebrow">/ Services</span>
            <h2 className="t-display-md" style={{ margin: 0, maxWidth: 720, textWrap: "balance" }}>
              Nos services
            </h2>
          </div>
        </div>

        <div className="bento" data-stagger>
          {/* Card 01 — Featured · Automatisations sur-mesure */}
          <ServiceFeatured
            n="01"
            title="Automatisations sur-mesure"
            desc="On automatise les tâches répétitives qui consomment le temps de vos équipes : service client, gestion d'emails, facturation et relances, suivi commercial, reporting hebdomadaire."
            tags={["Service client", "Emails", "Facturation", "Reporting", "Relances"]}
          />

          {/* Card 02 — Chatbot 24/7 */}
          <ServiceCard
            n="02"
            title="Chatbot qui travaille pour vous 24h/7j"
            desc="Un assistant intelligent sur votre site, vos emails ou WhatsApp. Il répond aux clients, qualifie les demandes et transmet les cas complexes à vos équipes."
            size="md"
            visual={<ChatIconVisual />}
          />

          {/* Card 03 — Solutions IA sur-mesure */}
          <ServiceCard
            n="03"
            title="Solutions IA sur-mesure"
            desc="Une application taillée pour votre métier, intégrée à vos outils. Vous restez 100% propriétaire du code et des données."
            size="md"
            visual={<CodeVisual />}
          />

          {/* Card 04 — Agent OpenClaw */}
          <ServiceCard
            n="04"
            title="Installation d'un agent OpenClaw"
            desc="On déploie OpenClaw sur votre infrastructure, on le connecte à vos outils internes et on configure les automatisations adaptées à votre métier."
            size="sm"
            visual={<AgentVisual />}
          />

          {/* Card 05 — Conseil & Formation */}
          <ServiceCard
            n="05"
            title="Conseil & formation"
            desc="Accompagnement de vos dirigeants sur la stratégie IA et formation concrète de vos équipes pour comprendre l'IA en profondeur et l'adopter dans leur quotidien."
            size="sm"
            visual={<TeamVisual />}
          />
        </div>

        <style>{`
          .bento {
            display: grid;
            grid-template-columns: repeat(12, minmax(0, 1fr));
            grid-auto-rows: 200px;
            gap: 12px;
            position: relative;
          }
          .bento > .bento-featured { grid-column: span 7; grid-row: span 2; }
          .bento > .bento-md       { grid-column: span 5; grid-row: span 1; }
          .bento > .bento-sm       { grid-column: span 6; grid-row: span 1; }
          .bento > * { min-width: 0; }

          @media (max-width: 1080px) {
            .bento > .bento-featured { grid-column: span 12; grid-row: span 2; }
            .bento > .bento-md       { grid-column: span 6; }
            .bento > .bento-sm       { grid-column: span 6; }
          }
          @media (max-width: 720px) {
            .bento {
              grid-template-columns: minmax(0, 1fr) !important;
              grid-auto-rows: auto;
              gap: 40px;
            }
            .bento > .bento-featured,
            .bento > .bento-md,
            .bento > .bento-sm {
              grid-column: auto !important;
              grid-row: auto !important;
              min-height: auto !important;
              min-width: 0 !important;
              z-index: 1;
            }

            /* Subtle red continuity line down the center, between cards only */
            .bento::before {
              content: "";
              position: absolute;
              top: 28px;
              bottom: 28px;
              left: 50%;
              transform: translateX(-50%);
              width: 1px;
              background: linear-gradient(180deg,
                transparent 0%,
                rgba(255, 51, 36, 0.5) 12%,
                rgba(255, 51, 36, 0.5) 88%,
                transparent 100%);
              opacity: 0.7;
              pointer-events: none;
              z-index: 0;
            }
          }
        `}</style>
      </div>
    </section>
  );
}

// ── Featured card with live chat animation ──────────────────────
function ServiceFeatured({ n, title, desc, tags }) {
  return (
    <article className="reveal interactive-card bento-featured" style={{
      background: "var(--canvas-card)",
      border: "1px solid var(--hairline)",
      borderRadius: "var(--radius-sm)",
      padding: 0,
      position: "relative",
      overflow: "hidden",
      display: "grid",
      gridTemplateColumns: "1fr 1.1fr",
      gap: 0,
    }}>
      {/* Left — content */}
      <div style={{ padding: 26, display: "flex", flexDirection: "column", gap: 14, position: "relative", zIndex: 1 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span className="t-mono-sm" style={{ color: "var(--accent)" }}>{n} · SERVICE</span>
          <ServiceIcon kind="flow" />
        </div>
        <h3 style={{
          margin: 0,
          fontSize: 22,
          letterSpacing: "-0.025em",
          lineHeight: 1.18,
          color: "var(--ink)",
        }}>{title}</h3>
        <p style={{ margin: 0, color: "var(--body)", fontSize: 14, lineHeight: 1.55, flex: 1 }}>{desc}</p>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 10 }}>
          {tags.map((t, i) => (
            <span key={i} style={{
              padding: "6px 12px",
              borderRadius: 9999,
              border: "1px solid var(--hairline)",
              fontFamily: "var(--font-mono)",
              fontSize: 11,
              letterSpacing: "0.08em",
              textTransform: "uppercase",
              color: "var(--body)",
              whiteSpace: "nowrap",
            }}>{t}</span>
          ))}
        </div>
      </div>

      {/* Right — animated automation feed */}
      <div className="bento-featured-right" style={{ position: "relative", padding: "26px 26px 26px 0", display: "flex", alignItems: "stretch" }}>
        <AutomationPreview />
      </div>

      <style>{`
        @media (max-width: 1080px) and (min-width: 721px) {
          .bento-featured-right { padding: 0 26px 26px 26px !important; }
        }
        @media (max-width: 720px) {
          .bento-featured { grid-template-columns: 1fr !important; }
          .bento-featured-right { padding: 0 22px 22px 22px !important; min-height: 220px; }
        }
      `}</style>
    </article>
  );
}

// ── Generic service card with visual ────────────────────────────
function ServiceCard({ n, title, desc, size, visual }) {
  return (
    <article className={`reveal interactive-card bento-${size}`} style={{
      background: "var(--canvas-card)",
      border: "1px solid var(--hairline)",
      borderRadius: "var(--radius-sm)",
      padding: 22,
      position: "relative",
      overflow: "hidden",
      display: "flex",
      flexDirection: "column",
      gap: 10,
    }}>
      {/* Visual — absolutely positioned top-right, doesn't push content */}
      <div style={{
        position: "absolute", top: 18, right: 18,
        width: 44, height: 44,
        opacity: 0.95,
        pointerEvents: "none",
        display: "flex", alignItems: "center", justifyContent: "center",
        zIndex: 1,
      }}>{visual}</div>

      {/* Number */}
      <span className="t-mono-sm" style={{ color: "var(--body-mid)", position: "relative", zIndex: 1 }}>{n}</span>

      {/* Title + desc — naturally at the top */}
      <div style={{ display: "flex", flexDirection: "column", gap: 6, position: "relative", zIndex: 1 }}>
        <h3 style={{
          margin: 0,
          fontSize: 17,
          letterSpacing: "-0.02em",
          lineHeight: 1.25,
          color: "var(--ink)",
          paddingRight: 52,
        }}>{title}</h3>
        <p style={{
          margin: 0, color: "var(--body)", fontSize: 13.5, lineHeight: 1.55,
        }}>{desc}</p>
      </div>
    </article>
  );
}

// ── Live automation feed (for the featured "Automatisation" card) ──
function AutomationPreview() {
  // Tasks cycle in slowly so the card feels alive without making scroll feel busy.
  // (visually: rows appear top-down, each row glows for ~600ms then settles).
  const tasks = [
    { in: "Email reçu · Dupont",         out: "Réponse envoyée",     kind: "email" },
    { in: "Facture #2453 en retard",     out: "Relance programmée",   kind: "invoice" },
    { in: "Demande de devis · Martin",   out: "Qualifiée · CRM mis à jour", kind: "lead" },
    { in: "Ticket support · Bernard",    out: "Réponse FAQ envoyée",  kind: "ticket" },
    { in: "Rapport hebdo demandé",       out: "Rapport généré · envoyé", kind: "report" },
  ];

  const [tick, setTick] = React.useState(0);
  const [count, setCount] = React.useState(127);
  React.useEffect(() => {
    const t = setInterval(() => {
      setTick(v => v + 1);
      setCount(c => c + Math.floor(1 + Math.random() * 3));
    }, 2600);
    return () => clearInterval(t);
  }, []);

  // Show the last 4 tasks (rolling window)
  const window = 4;
  const visible = Array.from({ length: window }).map((_, i) => {
    const taskIdx = (tick + i) % tasks.length;
    return { ...tasks[taskIdx], key: `${tick}-${i}` };
  });

  return (
    <div style={{
      flex: 1,
      background: "linear-gradient(180deg, var(--canvas-soft) 0%, var(--canvas-mid) 100%)",
      borderRadius: "var(--radius-sm)",
      border: "1px solid var(--hairline)",
      padding: 18,
      display: "flex",
      flexDirection: "column",
      gap: 12,
      overflow: "hidden",
      position: "relative",
    }}>
      {/* Scanning red beam */}
      <div className="automation-scan" style={{
        position: "absolute", left: 0, right: 0,
        height: 2,
        background: "linear-gradient(90deg, transparent, var(--accent), transparent)",
        filter: "drop-shadow(0 0 8px var(--accent-glow))",
        pointerEvents: "none",
        zIndex: 2,
      }} />

      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, position: "relative", zIndex: 1 }}>
        <span style={{
          width: 7, height: 7, borderRadius: "50%",
          background: "var(--accent)",
          boxShadow: "0 0 8px var(--accent-glow)",
          animation: "livePulse 1.4s ease-in-out infinite",
        }} />
        <span className="t-mono-sm" style={{ color: "var(--body)", fontSize: 10, whiteSpace: "nowrap" }}>FLUX D'AUTOMATISATION</span>
        <span style={{ flex: 1 }} />
        <span className="t-mono-sm" style={{ color: "var(--body-mid)", fontSize: 10, whiteSpace: "nowrap" }}>LIVE</span>
      </div>

      {/* Task list */}
      <div style={{ display: "flex", flexDirection: "column", gap: 8, flex: 1 }}>
        {visible.map((task, i) => (
          <TaskRow key={task.key} task={task} isNew={i === 0} fade={i === window - 1} />
        ))}
      </div>

      {/* Footer counter */}
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        paddingTop: 10,
        borderTop: "1px solid var(--hairline)",
      }}>
        <span className="t-mono-sm" style={{ color: "var(--body-mid)", fontSize: 10, whiteSpace: "nowrap" }}>AUJOURD'HUI</span>
        <span style={{
          fontFamily: "var(--font-display)",
          fontSize: 17,
          letterSpacing: "-0.02em",
          color: "var(--ink)",
          fontVariantNumeric: "tabular-nums",
        }}>
          {count}<span style={{ color: "var(--body-mid)", fontSize: 11, marginLeft: 4 }}>tâches automatisées</span>
        </span>
      </div>

      <style>{`
        @keyframes livePulse {
          0%, 100% { transform: scale(1); opacity: 1; }
          50% { transform: scale(1.22); opacity: 0.72; }
        }
        @keyframes taskIn {
          from { opacity: 0; transform: translateY(-4px); }
          to   { opacity: 1; transform: none; }
        }
        @keyframes scanBeam {
          0%   { top: 0; opacity: 0; }
          14%  { opacity: 0.75; }
          86%  { opacity: 0.75; }
          100% { top: 100%; opacity: 0; }
        }
        .automation-scan { animation: scanBeam 5.8s ease-in-out infinite; }
      `}</style>
    </div>
  );
}

function TaskRow({ task, isNew, fade }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "1fr 18px 1fr",
      alignItems: "center",
      gap: 8,
      padding: "8px 10px",
      borderRadius: 7,
      background: isNew ? "rgba(255, 51, 36, 0.08)" : "rgba(255,255,255,0.03)",
      border: isNew ? "1px solid rgba(255, 51, 36, 0.25)" : "1px solid var(--hairline)",
      opacity: fade ? 0.45 : 1,
      animation: isNew ? "taskIn 0.8s var(--ease-reveal) both" : undefined,
      transition: "opacity 0.8s var(--ease-ui)",
    }}>
      <div style={{
        fontSize: 11.5, lineHeight: 1.3,
        color: "var(--ink)",
        overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
      }}>{task.in}</div>
      <svg width="14" height="14" viewBox="0 0 12 12" fill="none" style={{ color: "var(--accent)", justifySelf: "center" }}>
        <path d="M2 6h7m-3-3 3 3-3 3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
      <div style={{
        fontSize: 11.5, lineHeight: 1.3,
        color: "var(--body)",
        overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
      }}>{task.out}</div>
    </div>
  );
}

// ── Service mini-visuals ────────────────────────────────────────
function ChatIconVisual() {
  // Two chat bubbles, the bottom one with typing dots
  return (
    <svg width="56" height="56" viewBox="0 0 56 56" fill="none">
      <rect x="6" y="8" width="32" height="20" rx="6" stroke="var(--ink)" strokeWidth="1.4" />
      <circle cx="18" cy="18" r="1.6" fill="var(--ink)" opacity="0.6" />
      <circle cx="24" cy="18" r="1.6" fill="var(--ink)" opacity="0.6" />
      <circle cx="30" cy="18" r="1.6" fill="var(--ink)" opacity="0.6" />
      <path d="M14 28 L11 33 L20 28" stroke="var(--ink)" strokeWidth="1.4" strokeLinejoin="round" />

      <rect x="20" y="30" width="30" height="18" rx="6" fill="color-mix(in oklab, var(--accent) 16%, transparent)" stroke="var(--accent)" strokeWidth="1.4" />
      <circle cx="29" cy="39" r="1.8" fill="var(--accent)">
        <animate attributeName="opacity" values="0.3;1;0.3" dur="1.4s" repeatCount="indefinite" />
      </circle>
      <circle cx="35" cy="39" r="1.8" fill="var(--accent)">
        <animate attributeName="opacity" values="0.3;1;0.3" dur="1.4s" begin="0.2s" repeatCount="indefinite" />
      </circle>
      <circle cx="41" cy="39" r="1.8" fill="var(--accent)">
        <animate attributeName="opacity" values="0.3;1;0.3" dur="1.4s" begin="0.4s" repeatCount="indefinite" />
      </circle>
      <path d="M44 48 L47 53 L38 48" fill="color-mix(in oklab, var(--accent) 16%, transparent)" stroke="var(--accent)" strokeWidth="1.4" strokeLinejoin="round" />
    </svg>
  );
}

function CodeVisual() {
  // Modular blocks — represents custom-fit / tailor-made solutions
  return (
    <svg width="56" height="56" viewBox="0 0 56 56" fill="none">
      <rect x="6" y="6" width="20" height="20" rx="3" stroke="var(--ink)" strokeWidth="1.4" opacity="0.85" />
      <rect x="30" y="6" width="20" height="20" rx="3"
        fill="color-mix(in oklab, var(--accent) 18%, transparent)"
        stroke="var(--accent)" strokeWidth="1.4">
        <animate attributeName="opacity" values="1;0.6;1" dur="2s" repeatCount="indefinite" />
      </rect>
      <rect x="6" y="30" width="20" height="20" rx="3"
        fill="color-mix(in oklab, var(--accent) 18%, transparent)"
        stroke="var(--accent)" strokeWidth="1.4">
        <animate attributeName="opacity" values="0.6;1;0.6" dur="2s" repeatCount="indefinite" />
      </rect>
      <rect x="30" y="30" width="20" height="20" rx="3" stroke="var(--ink)" strokeWidth="1.4" opacity="0.85" />
      <circle cx="28" cy="28" r="2.5" fill="var(--accent)">
        <animate attributeName="r" values="2.5;3.6;2.5" dur="1.4s" repeatCount="indefinite" />
      </circle>
    </svg>
  );
}

function AgentVisual() {
  // OpenClaw real logo, gentle float + subtle rotation
  return (
    <>
      <img
        src="openclaw.svg"
        alt="OpenClaw"
        width="44"
        height="44"
        style={{
          display: "block",
          filter: "drop-shadow(0 0 14px rgba(255, 51, 36, 0.45))",
          animation: "openClawBob 3.6s ease-in-out infinite",
        }}
      />
      <style>{`
        @keyframes openClawBob {
          0%, 100% { transform: translateY(0) rotate(-4deg); }
          50%      { transform: translateY(-3px) rotate(4deg); }
        }
      `}</style>
    </>
  );
}

function TeamVisual() {
  // Idea spark — radiating beam representing knowledge transfer
  return (
    <svg width="56" height="56" viewBox="0 0 56 56" fill="none">
      <circle cx="28" cy="28" r="16" stroke="var(--ink)" strokeWidth="1.2" opacity="0.3" strokeDasharray="2 3" />
      <circle cx="28" cy="28" r="9"
        fill="color-mix(in oklab, var(--accent) 22%, transparent)"
        stroke="var(--accent)" strokeWidth="1.4" />
      <circle cx="28" cy="28" r="3.5" fill="var(--accent)">
        <animate attributeName="r" values="3.5;5.5;3.5" dur="1.6s" repeatCount="indefinite" />
        <animate attributeName="opacity" values="1;0.55;1" dur="1.6s" repeatCount="indefinite" />
      </circle>
      <line x1="28" y1="4" x2="28" y2="10" stroke="var(--accent)" strokeWidth="1.6" strokeLinecap="round" opacity="0.85" />
      <line x1="28" y1="46" x2="28" y2="52" stroke="var(--accent)" strokeWidth="1.6" strokeLinecap="round" opacity="0.85" />
      <line x1="4" y1="28" x2="10" y2="28" stroke="var(--accent)" strokeWidth="1.6" strokeLinecap="round" opacity="0.85" />
      <line x1="46" y1="28" x2="52" y2="28" stroke="var(--accent)" strokeWidth="1.6" strokeLinecap="round" opacity="0.85" />
      <line x1="11" y1="11" x2="15.5" y2="15.5" stroke="var(--ink)" strokeWidth="1.2" strokeLinecap="round" opacity="0.45" />
      <line x1="40.5" y1="40.5" x2="45" y2="45" stroke="var(--ink)" strokeWidth="1.2" strokeLinecap="round" opacity="0.45" />
      <line x1="45" y1="11" x2="40.5" y2="15.5" stroke="var(--ink)" strokeWidth="1.2" strokeLinecap="round" opacity="0.45" />
      <line x1="15.5" y1="40.5" x2="11" y2="45" stroke="var(--ink)" strokeWidth="1.2" strokeLinecap="round" opacity="0.45" />
    </svg>
  );
}

function ServiceIcon({ kind }) {
  const common = { width: 24, height: 24, viewBox: "0 0 28 28", fill: "none" };
  const stroke = { stroke: "var(--ink)", strokeWidth: 1.2, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (kind) {
    case "flow":
      return <svg {...common}>
        <circle cx="6"  cy="14" r="3" {...stroke} />
        <circle cx="22" cy="7"  r="3" stroke="var(--accent)" strokeWidth="1.2" />
        <circle cx="22" cy="21" r="3" {...stroke} />
        <path d="M9 13 L19 8 M9 15 L19 20" {...stroke} />
      </svg>;
    default: return null;
  }
}

window.Services = Services;
