// ─────────────────────────────────────────────────────────────────────
// SUB-SOLUTION TEMPLATE (generic)
//
// One template renders every sub-solution detail page. It reads its
// data from window.__subSolution, which is populated server-side by
// src/pages/[parentSlug]/[slug].astro from the `sub-solutions` content
// collection.
//
// Page rhythm — same as the approved Custom Data Collection.html mock:
//   Hero → Overview → Use Cases → Why Argos → Outcome → Related
//
// window.__subSolution shape:
// {
//   solution: { …full frontmatter for THIS sub-solution… },
//   featured: [ {title, slug, parentSlug, parentCategory, icon, shortDescription}, … ],
//   siblings: [ {title, slug, parentSlug, icon, shortDescription}, … ],
// }
//
// Featured cards render with a navy bg + white text (cross-category
// spotlights). Sibling cards render with the standard cream-on-white
// treatment. Both appear in the same Related grid; featured first.
// ─────────────────────────────────────────────────────────────────────

const D = (typeof window !== 'undefined' && window.__subSolution)
  ? window.__subSolution
  : { solution: {}, featured: [], siblings: [] };

const S = D.solution || {};

// Two-line title helper. The author MAY define overrides via a manual `\n`
// in the .md title field, but since titles in frontmatter are single-line
// strings, we auto-split at the natural midpoint for the hero/card titles
// to preserve the visual rhythm of the reference design ("Custom Data\nCollection").
function autoBreak(title) {
  if (!title) return '';
  if (title.includes('\n')) return title; // already broken
  const words = title.split(' ');
  if (words.length <= 1) return title;
  // Find the split point closest to half the word count
  const mid = Math.ceil(words.length / 2);
  return words.slice(0, mid).join(' ') + '\n' + words.slice(mid).join(' ');
}

// Derived headlines — used when frontmatter doesn't override them.
function defaultOverviewHeadline(solution) {
  return solution.overviewHeadline || `${solution.title}, treated as an engineered data discipline.`;
}
function defaultUseCasesHeadline(solution) {
  return solution.useCasesHeadline || `Where ${solution.title} is applied.`;
}
function defaultWhyArgosHeadline(solution) {
  return solution.whyArgosHeadline || `Why ${solution.title} delivers in production.`;
}
function defaultOutcomeHeadline(solution) {
  return solution.outcomeHeadline || `Outcomes that move from pilot to production.`;
}

// Helpers to read overview/outcome paragraph bodies.
function overviewParagraph(solution) {
  const e = solution.expandedDescription || [];
  return e[1] || e[0] || '';
}


// ── HERO ─────────────────────────────────────────────────────────────
const SubServiceHero = ({ onCTA }) => (
  <section data-screen-label="Hero" className="full-bleed" style={{
    position: "relative",
    minHeight: "min(680px, 88svh)",
    padding: "clamp(140px, 16vh, 220px) clamp(20px, 6vw, 96px) clamp(56px, 8vh, 96px)",
    fontFamily: "var(--font-display)",
    color: "#0E1F3E",
    overflow: "hidden",
    display: "flex", flexDirection: "column",
    background: "#F6F4EC",
  }}>
    <div aria-hidden="true" style={{
      position: "absolute", inset: 0,
      background:
        "radial-gradient(60% 70% at 78% 50%, rgba(238,227,107,0.32) 0%, rgba(238,227,107,0.10) 38%, rgba(246,244,236,0) 72%)",
      pointerEvents: "none",
    }} />
    <div aria-hidden="true" style={{
      position: "absolute", top: 0, left: 96, right: 96,
      height: 1, background: "rgba(14,31,62,0.14)",
    }} />

    <div style={{
      position: "relative", maxWidth: 1600, margin: "0 auto",
      width: "100%", flex: 1,
      display: "grid", gridTemplateColumns: "1.35fr 1fr",
      columnGap: 80, alignItems: "end",
    }}>
      {/* LEFT — type column */}
      <div>
        <nav aria-label="Breadcrumb" style={{
          display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap",
          fontSize: 12, fontWeight: 500, letterSpacing: "0.02em",
          color: "rgba(14,31,62,0.65)", marginBottom: 28,
        }}>
          <a href="/" style={{ textDecoration: "none" }}>Solutions</a>
          <span aria-hidden="true" style={{ opacity: 0.45 }}>/</span>
          <a href={`/${S.parentSlug}/`} style={{ textDecoration: "none" }}>{S.parentCategory}</a>
          <span aria-hidden="true" style={{ opacity: 0.45 }}>/</span>
          <span style={{ color: "#0E1F3E" }}>{S.title}</span>
        </nav>

        <h1 style={{
          fontWeight: 700, lineHeight: 1.02,
          letterSpacing: "-0.03em", margin: 0, maxWidth: 1000,
          textWrap: "balance",
          color: "#0E1F3E", fontSize: 72,
        }}>{S.title}</h1>

        <p style={{
          margin: "28px 0 0", maxWidth: 580, fontSize: 17, lineHeight: 1.55,
          fontWeight: 400, color: "rgba(14,31,62,0.78)",
        }}>{S.shortDescription}</p>

        <div style={{ display: "flex", gap: 12, marginTop: 40 }}>
          <button onClick={onCTA} style={{
            background: "#0E1F3E", color: "#FFFFFF",
            padding: "14px 24px", borderRadius: 37, fontSize: 13, fontWeight: 500,
            fontFamily: "var(--font-display)",
            border: "1px solid #0E1F3E", cursor: "pointer",
            display: "inline-flex", alignItems: "center", gap: 10,
            letterSpacing: "-0.005em",
          }}>Talk to an expert</button>
          <button onClick={() => {
            const el = document.getElementById('use-cases');
            if (!el) return;
            const y = el.getBoundingClientRect().top + window.scrollY;
            window.scrollTo({ top: y, behavior: 'smooth' });
          }} style={{
            background: "transparent", color: "#0E1F3E",
            padding: "14px 24px", borderRadius: 37, fontSize: 13, fontWeight: 500,
            fontFamily: "var(--font-display)",
            border: "1px solid rgba(14,31,62,0.32)", cursor: "pointer",
            display: "inline-flex", alignItems: "center", gap: 10,
            letterSpacing: "-0.005em",
          }}>See use cases</button>
        </div>
      </div>

      {/* RIGHT — icon plate */}
      <div style={{
        position: "relative",
        aspectRatio: "1 / 1",
        maxWidth: 460, justifySelf: "end", width: "100%",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <div style={{
          position: "absolute", inset: 0,
          borderRadius: 32,
          background: "linear-gradient(180deg, rgba(255,255,255,0.6) 0%, rgba(255,255,255,0.0) 100%)",
          border: "1px solid rgba(14,31,62,0.10)",
          boxShadow: "inset 0 1px 0 rgba(255,255,255,0.8)",
        }} />
        <div style={{
          position: "absolute", top: 20, left: 24,
          fontSize: 11, fontWeight: 500, letterSpacing: "0.08em",
          color: "rgba(14,31,62,0.45)",
          fontFeatureSettings: '"tnum"',
        }}>{String(S.order || 1).padStart(2, "0")}</div>
        <div style={{ width: "58%", height: "58%", position: "relative" }}>
          <SvcIcon name={S.icon} stroke="#0E1F3E" strokeWidth={1.6} />
        </div>
      </div>
    </div>
  </section>
);


// ── OVERVIEW ─────────────────────────────────────────────────────────
const Overview = () => (
  <section data-screen-label="Overview" className="full-bleed" style={{
    fontFamily: "var(--font-display)",
    color: "#0E1F3E",
    padding: "clamp(60px, 10vw, 120px) clamp(20px, 6vw, 96px) clamp(60px, 10vw, 120px)", background: "rgb(255, 255, 255)",
  }}>
    <div style={{ maxWidth: 1600, margin: "0 auto" }}>
      <div style={{
        fontSize: 13, fontWeight: 500, color: "#666",
        letterSpacing: "0.10em", textTransform: "uppercase",
        marginBottom: 24,
      }}>Overview</div>
      <h2 style={{
        fontSize: 48, fontWeight: 700, lineHeight: 1.06,
        letterSpacing: "-0.025em", margin: "0 0 44px",
        maxWidth: 1100, textWrap: "balance",
      }}>{defaultOverviewHeadline(S)}</h2>
      <p style={{
        fontSize: 20, lineHeight: 1.5, color: "#1A1A1A",
        fontWeight: 400, margin: 0, maxWidth: 960,
      }}>{overviewParagraph(S)}</p>
    </div>
  </section>
);


// ── USE CASES ────────────────────────────────────────────────────────
const UseCases = () => {
  const items = S.useCases || [];
  return (
    <section id="use-cases" data-screen-label="Use cases" style={{
      fontFamily: "var(--font-display)",
      background: "#FFFFFF", color: "#0E1F3E",
      padding: "clamp(60px, 10vw, 120px) clamp(20px, 6vw, 96px) clamp(60px, 10vw, 120px)",
    }}>
      <div style={{ maxWidth: 1600, margin: "0 auto" }}>
        <div style={{
          fontSize: 13, fontWeight: 500, color: "#666",
          letterSpacing: "0.10em", textTransform: "uppercase",
          marginBottom: 24,
        }}>Use cases</div>
        <h2 style={{
          fontSize: 48, fontWeight: 700, lineHeight: 1.06,
          letterSpacing: "-0.025em", margin: "0 0 56px",
          maxWidth: 1100, textWrap: "balance",
        }}>{defaultUseCasesHeadline(S)}</h2>
        <div style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          columnGap: 64,
          borderTop: "1px solid rgba(14,31,62,0.30)",
        }}>
          {items.map((it, i) => (
            <div key={it} style={{
              display: "grid",
              gridTemplateColumns: "60px 1fr",
              gap: 24,
              padding: "32px 0",
              borderBottom: "1px solid rgba(14,31,62,0.18)",
              alignItems: "baseline",
            }}>
              <div style={{
                fontSize: 15, fontWeight: 500, color: "#0E1F3E",
                fontFeatureSettings: '"tnum"', opacity: 0.55,
              }}>{String(i + 1).padStart(2, "0")}</div>
              <div style={{
                fontSize: 22, lineHeight: 1.3, fontWeight: 500,
                letterSpacing: "-0.01em", color: "#0E1F3E", textWrap: "balance",
              }}>{it}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};


// ── WHY ARGOS / DIFFERENTIATOR ───────────────────────────────────────
const WhyArgos = () => {
  const blocks = (S.differentiator || []).map(b => ({ id: b.label, body: b.body }));
  return (
    <section data-screen-label="Why Argos" data-nav-tone="dark" className="full-bleed" style={{
      padding: "clamp(60px, 10vw, 120px) clamp(20px, 6vw, 96px)", fontFamily: "var(--font-display)",
      background: "#0E1F3E", color: "#fff",
    }}>
      <div style={{ maxWidth: 1600, margin: "0 auto" }}>
        <div style={{
          fontSize: 13, fontWeight: 500, color: "rgba(255,255,255,0.55)",
          letterSpacing: "0.10em", textTransform: "uppercase", marginBottom: 24,
        }}>Why Argos</div>
        <h2 style={{
          fontSize: 48, fontWeight: 700, lineHeight: 1.06,
          letterSpacing: "-0.025em", margin: "0 0 64px",
          maxWidth: 1100, textWrap: "balance",
        }}>{defaultWhyArgosHeadline(S)}</h2>
        <div style={{
          display: "grid",
          gridTemplateColumns: `repeat(${Math.max(1, blocks.length)}, 1fr)`,
          gap: 0,
          borderTop: "1px solid rgba(255,255,255,0.18)",
        }}>
          {blocks.map((v, i) => (
            <div key={v.id || i} style={{
              padding: "44px 36px 44px 0",
              paddingLeft: i === 0 ? 0 : 36,
              borderRight: i < blocks.length - 1 ? "1px solid rgba(255,255,255,0.18)" : "none",
            }}>
              <div style={{
                fontSize: 30, fontWeight: 700, lineHeight: 1.05,
                letterSpacing: "-0.02em", marginBottom: 22,
              }}>{v.id}</div>
              <p style={{
                fontSize: 16, lineHeight: 1.55, color: "rgba(255,255,255,0.78)",
                fontWeight: 400, margin: 0,
              }}>{v.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};


// ── OUTCOME ──────────────────────────────────────────────────────────
const Outcome = () => (
  <section data-screen-label="Outcome" className="full-bleed" style={{
    padding: "clamp(60px, 10vw, 120px) clamp(20px, 6vw, 96px)", fontFamily: "var(--font-display)",
    background: "#F2F2F0", color: "#0E1F3E",
  }}>
    <div style={{ maxWidth: 1600, margin: "0 auto" }}>
      <div style={{
        fontSize: 13, fontWeight: 500, color: "#666",
        letterSpacing: "0.10em", textTransform: "uppercase", marginBottom: 24,
      }}>Outcome</div>
      <h2 style={{
        fontSize: 48, fontWeight: 700, lineHeight: 1.06,
        letterSpacing: "-0.025em", margin: "0 0 44px",
        maxWidth: 1200, textWrap: "balance",
      }}>{defaultOutcomeHeadline(S)}</h2>
      <p style={{
        fontSize: 20, lineHeight: 1.5, color: "#1A1A1A",
        fontWeight: 400, maxWidth: 980, margin: 0, textWrap: "pretty",
      }}>{S.outcome}</p>
    </div>
  </section>
);


// ── RELATED SUB-SERVICES ────────────────────────────────────────────
const RelatedSubServices = () => {
  const featured = D.featured || [];
  const siblings = D.siblings || [];

  return (
    <section data-screen-label="Related sub-services" style={{
      fontFamily: "var(--font-display)",
      background: "#FFFFFF", color: "#0E1F3E",
      padding: "clamp(60px, 10vw, 120px) clamp(20px, 6vw, 96px) clamp(60px, 12vw, 140px)",
    }}>
      <div style={{ maxWidth: 1600, margin: "0 auto" }}>
        <div style={{
          display: "flex", justifyContent: "space-between",
          alignItems: "flex-end", gap: 32, marginBottom: 56,
          flexWrap: "wrap",
        }}>
          <div>
            <div style={{
              fontSize: 13, fontWeight: 500, color: "#666",
              letterSpacing: "0.10em", textTransform: "uppercase",
              marginBottom: 20,
            }}>More in {S.parentCategory}</div>
            <h2 style={{
              fontSize: 40, fontWeight: 700, lineHeight: 1.08,
              letterSpacing: "-0.025em", margin: 0, maxWidth: 720,
              textWrap: "balance",
            }}>Related solutions.</h2>
          </div>
          <a href={`/${S.parentSlug}/`} style={{
            fontSize: 13, fontWeight: 500, color: "#0E1F3E",
            textDecoration: "none",
            display: "inline-flex", alignItems: "center", gap: 8,
            borderBottom: "1px solid #0E1F3E", paddingBottom: 3,
          }} data-arrow="left">
            <span aria-hidden="true" className="arrow">←</span>
            {` Back to ${S.parentCategory}`}
          </a>
        </div>

        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(260px, 360px))",
          justifyContent: "start",
          gap: 16,
          alignItems: "stretch",
        }}>
          {/* Featured cards — navy bg, white text */}
          {featured.map((s) => (
            <a key={`f-${s.slug}`} href={`/${s.parentSlug}/${s.slug}/`} style={{
              border: "1px solid #0E1F3E",
              borderRadius: 20,
              padding: "24px 22px 22px",
              background: "#0E1F3E",
              display: "flex", flexDirection: "column",
              gap: 18, textDecoration: "none",
              color: "#FFFFFF",
              transition: "background 160ms ease, transform 160ms ease, border-color 160ms ease",
              minHeight: 260, position: "relative", overflow: "hidden",
            }}
            data-arrow="right"
            onMouseEnter={(e) => { e.currentTarget.style.background = "#172A4D"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "#0E1F3E"; }}>
              <div aria-hidden="true" style={{
                position: "absolute", inset: 0,
                background:
                  "radial-gradient(120% 80% at 100% 0%, rgba(238,227,107,0.10) 0%, rgba(238,227,107,0) 60%)",
                pointerEvents: "none",
              }} />
              <div style={{
                position: "relative", display: "flex",
                alignItems: "center", justifyContent: "space-between", gap: 12,
              }}>
                <div style={{ width: 36, height: 36 }}>
                  <SvcIcon name={s.icon} stroke="#FFFFFF" strokeWidth={1.8} />
                </div>
                <div style={{
                  fontSize: 10, fontWeight: 500, letterSpacing: "0.10em",
                  textTransform: "uppercase",
                  color: "rgba(255,255,255,0.6)",
                }}>{s.parentCategory}</div>
              </div>
              <div style={{
                fontSize: 18, fontWeight: 700, lineHeight: 1.2,
                letterSpacing: "-0.012em", whiteSpace: "pre-line",
                position: "relative",
              }}>{autoBreak(s.title)}</div>
              <p style={{
                fontSize: 13, lineHeight: 1.5,
                color: "rgba(255,255,255,0.78)", fontWeight: 400, margin: 0,
                position: "relative",
              }}>{s.shortDescription}.</p>
              <div style={{
                marginTop: "auto", paddingTop: 8,
                display: "inline-flex", alignItems: "center", gap: 6,
                fontSize: 12, fontWeight: 500, letterSpacing: "0.02em",
                color: "#FFFFFF", position: "relative",
              }}>
                Learn more <span aria-hidden="true" className="arrow">→</span>
              </div>
            </a>
          ))}

          {/* Sibling cards — light, standard treatment */}
          {siblings.map((s) => (
            <a key={`s-${s.slug}`} href={`/${s.parentSlug}/${s.slug}/`} style={{
              border: "1px solid rgba(14,31,62,0.22)",
              borderRadius: 20,
              padding: "24px 22px 22px",
              background: "#FFFFFF",
              display: "flex", flexDirection: "column",
              gap: 18, textDecoration: "none",
              color: "#0E1F3E",
              transition: "border-color 160ms ease, transform 160ms ease, background 160ms ease",
              minHeight: 260,
            }}
            data-arrow="right"
            onMouseEnter={(e) => {
              e.currentTarget.style.borderColor = "rgba(14,31,62,0.55)";
              e.currentTarget.style.background = "#FAF8F1";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.borderColor = "rgba(14,31,62,0.22)";
              e.currentTarget.style.background = "#FFFFFF";
            }}>
              <div style={{ width: 36, height: 36 }}>
                <SvcIcon name={s.icon} stroke="#0E1F3E" strokeWidth={1.8} />
              </div>
              <div style={{
                fontSize: 18, fontWeight: 700, lineHeight: 1.2,
                letterSpacing: "-0.012em", whiteSpace: "pre-line",
              }}>{autoBreak(s.title)}</div>
              <p style={{
                fontSize: 13, lineHeight: 1.5,
                color: "#1A1A1A", fontWeight: 400, margin: 0,
              }}>{s.shortDescription}.</p>
              <div style={{
                marginTop: "auto", paddingTop: 8,
                display: "inline-flex", alignItems: "center", gap: 6,
                fontSize: 12, fontWeight: 500, letterSpacing: "0.02em",
              }}>
                Learn more <span aria-hidden="true" className="arrow">→</span>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
};


// ── ROOT APP ─────────────────────────────────────────────────────────
function SubSolutionApp() {
  const goCTA = () => { window.location.href = '/contact-us/'; };
  return (
    <div>
      <SubServiceHero onCTA={goCTA} />
      <Overview />
      <UseCases />
      <WhyArgos />
      <Outcome />
      <RelatedSubServices />
    </div>
  );
}

window.SubSolutionApp = SubSolutionApp;
