// ============================================================
// autoclient.io: REUSABLE FLAGSHIP SERVICE PAGE MODULES
// Shared editorial depth blocks for upgraded service pages:
//   ContrarianComparison, ChannelDiagnostic, QualificationSplit,
//   SpecialistProofStrip, RelatedProofGrid, ServiceFaqSection.
// All cross-module globals (TEAM, CASES, BLOG_POSTS) are resolved
// defensively at render time so script load order never breaks.
// ============================================================
(() => {
  const { useState: useSmState } = React;

  function SectionIntro({ eyebrow, heading, intro }) {
    const OverlineComp = window.Overline;
    if (!eyebrow && !heading && !intro) return null;
    return (
      <div className="sm-intro">
        {eyebrow && (OverlineComp ? <OverlineComp grad>{eyebrow}</OverlineComp> : <span className="overline-grad">{eyebrow}</span>)}
        {heading && <h2 className="sm-heading">{heading}</h2>}
        {intro && <p className="sm-sub">{intro}</p>}
      </div>
    );
  }

  /* ============================================================
     1. ContrarianComparison — Standard Agency vs AutoClient
     ============================================================ */
  function ContrarianComparison({
    eyebrow = "How we think differently",
    heading,
    intro,
    leftLabel = "Standard Agency Playbook",
    rightLabel = "How AutoClient Engineers It",
    rows = []
  }) {
    const safeRows = Array.isArray(rows) ? rows.filter(Boolean) : [];
    const IconComp = window.Icon;
    if (!safeRows.length) return null;

    return (
      <section className="sec sm-section">
        <div className="wrap-wide">
          <SectionIntro eyebrow={eyebrow} heading={heading} intro={intro} />
          <div className="sm-compare" role="region" aria-label={heading || "Comparison"}>
            <div className="sm-compare-head" aria-hidden="true">
              <div className="sm-compare-col-label is-muted">{leftLabel}</div>
              <div className="sm-compare-col-label is-brand">{rightLabel}</div>
            </div>
            <div className="sm-compare-rows">
              {safeRows.map((row, i) => {
                const topic = Array.isArray(row) ? row[0] : (row.topic || row.dimension || row.label || "");
                const standard = Array.isArray(row) ? row[1] : (row.standard || row.agency || row.before || "");
                const autoclient = Array.isArray(row) ? row[2] : (row.autoclient || row.ours || row.after || "");
                return (
                  <div key={i} className="sm-compare-row">
                    <div className="sm-compare-cell is-standard">
                      {topic && <div className="sm-compare-topic">{topic}</div>}
                      <div className="sm-compare-mobile-tag">{leftLabel}</div>
                      <div className="sm-compare-body">
                        <span className="sm-compare-icon is-muted" aria-hidden="true">
                          {IconComp ? <IconComp name="minus" size={14} /> : "—"}
                        </span>
                        <span>{standard}</span>
                      </div>
                    </div>
                    <div className="sm-compare-cell is-autoclient">
                      {topic && <div className="sm-compare-topic sm-compare-topic-ghost" aria-hidden="true">{topic}</div>}
                      <div className="sm-compare-mobile-tag is-brand">{rightLabel}</div>
                      <div className="sm-compare-body">
                        <span className="sm-compare-icon is-brand" aria-hidden="true">
                          {IconComp ? <IconComp name="check" size={14} /> : "✓"}
                        </span>
                        <span>{autoclient}</span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </section>
    );
  }

  /* ============================================================
     2. ChannelDiagnostic — Interactive 5-Minute Leak Self-Audit
     ============================================================ */
  function ChannelDiagnostic({
    eyebrow = "5-minute self-audit",
    heading,
    intro,
    items = [],
    ctaLabel = "Request a free teardown",
    ctaHref = "/contact"
  }) {
    const safeItems = Array.isArray(items) ? items.filter(Boolean) : [];
    const [flagged, setFlagged] = useSmState({});
    const IconComp = window.Icon;
    const ButtonComp = window.Button;
    if (!safeItems.length) return null;

    const toggleItem = (idx) => {
      setFlagged((prev) => ({ ...prev, [idx]: !prev[idx] }));
    };

    const count = Object.values(flagged).filter(Boolean).length;
    const statusText = count === 0
      ? "Click any warning sign you recognize to calculate your audit priority."
      : count === 1
        ? "1 leak flagged — usually enough to recover 15–25% of wasted budget or lost visibility."
        : `${count} of ${safeItems.length} leaks flagged — fixing these typically pays for the rebuild in the first 60 days.`;

    return (
      <section className="sec sm-section">
        <div className="wrap-wide">
          <SectionIntro eyebrow={eyebrow} heading={heading} intro={intro} />
          <div className="sm-diag">
            <div className="sm-diag-list">
              {safeItems.map((raw, i) => {
                const it = typeof raw === "string" ? { title: raw } : raw;
                const isOn = !!flagged[i];
                return (
                  <button
                    key={i}
                    type="button"
                    aria-pressed={isOn}
                    className={"sm-diag-item" + (isOn ? " is-flagged" : "")}
                    onClick={() => toggleItem(i)}
                  >
                    <span className="sm-diag-check" aria-hidden="true">
                      {isOn ? (IconComp ? <IconComp name="check" size={15} /> : "✓") : String(i + 1).padStart(2, "0")}
                    </span>
                    <span className="sm-diag-copy">
                      <span className="sm-diag-title">{it.title || it.check}</span>
                      {(it.detail || it.signal || it.desc) && (
                        <span className="sm-diag-desc">{it.detail || it.signal || it.desc}</span>
                      )}
                      {it.fix && (
                        <span className="sm-diag-fix">
                          <strong>What to look for:</strong> {it.fix}
                        </span>
                      )}
                    </span>
                    <span className="sm-diag-state">{isOn ? "Flagged" : "Flag issue"}</span>
                  </button>
                );
              })}
            </div>
            <div className="sm-diag-bar" role="status" aria-live="polite">
              <div className="sm-diag-summary">
                <span className="sm-diag-count">{count} / {safeItems.length} flagged</span>
                <span className="sm-diag-msg">{statusText}</span>
              </div>
              {ButtonComp ? (
                <ButtonComp variant="primary" size="sm" icon="arrow-right" href={ctaHref}>{ctaLabel}</ButtonComp>
              ) : (
                <a href={ctaHref} className="btn btn-primary btn-sm">{ctaLabel}</a>
              )}
            </div>
          </div>
        </div>
      </section>
    );
  }

  /* ============================================================
     3. QualificationSplit — Honest Fit vs Skip
     ============================================================ */
  function QualificationSplit({
    eyebrow = "Honest qualification",
    heading = "Who this works for — and who should wait.",
    intro,
    goodFitTitle = "We're a strong fit when",
    goodFit = [],
    skipTitle = "You should probably skip us if",
    skipItems = []
  }) {
    const good = Array.isArray(goodFit) ? goodFit.filter(Boolean) : [];
    const skip = Array.isArray(skipItems) ? skipItems.filter(Boolean) : [];
    const IconComp = window.Icon;
    if (!good.length && !skip.length) return null;

    const renderList = (list, tone) => (
      <ul className="sm-qual-list">
        {list.map((raw, i) => {
          const item = typeof raw === "string" ? { title: raw } : raw;
          return (
            <li key={i} className="sm-qual-li">
              <span className={"sm-qual-dot is-" + tone} aria-hidden="true">
                {IconComp ? <IconComp name={tone === "good" ? "check" : "x"} size={14} /> : (tone === "good" ? "✓" : "×")}
              </span>
              <span>
                <strong className="sm-qual-item-title">{item.title}</strong>
                {item.detail && <span className="sm-qual-item-detail"> — {item.detail}</span>}
              </span>
            </li>
          );
        })}
      </ul>
    );

    return (
      <section className="sec sm-section">
        <div className="wrap-wide">
          <SectionIntro eyebrow={eyebrow} heading={heading} intro={intro} />
          <div className="sm-qual">
            <div className="sm-qual-card is-good">
              <div className="sm-qual-kicker is-good">Best fit</div>
              <h3 className="sm-qual-title">{goodFitTitle}</h3>
              {renderList(good, "good")}
            </div>
            <div className="sm-qual-card is-skip">
              <div className="sm-qual-kicker is-skip">Not yet</div>
              <h3 className="sm-qual-title">{skipTitle}</h3>
              {renderList(skip, "skip")}
            </div>
          </div>
        </div>
      </section>
    );
  }

  function resolveProof(caseSlugs, blogSlugs) {
    const casesList = Array.isArray(window.CASES) ? window.CASES : [];
    const caseBySlug = window.CASE_BY_SLUG || Object.fromEntries(casesList.map((c) => [c.slug, c]));
    const blogList = Array.isArray(window.BLOG_POSTS) ? window.BLOG_POSTS : [];
    const blogBySlug = window.BLOG_BY_SLUG || Object.fromEntries(blogList.map((p) => [p.slug, p]));
    const resolvedCases = (Array.isArray(caseSlugs) ? caseSlugs : [])
      .map((s) => caseBySlug[s])
      .filter(Boolean);
    const resolvedBlogs = (Array.isArray(blogSlugs) ? blogSlugs : [])
      .map((s) => blogBySlug[s])
      .filter(Boolean);
    return { resolvedCases, resolvedBlogs };
  }

  /* ============================================================
     4. RelatedProofGrid — Real Case Studies + Typographic Blog Guides
        (ZERO Unsplash / stock heroImage rendering)
     ============================================================ */
  function RelatedProofGrid({
    eyebrow = "Proof & field notes",
    heading = "Related results and playbooks.",
    intro,
    caseSlugs = [],
    blogSlugs = [],
    embedded = false
  }) {
    const repNote = window.REPRESENTATIVE_NOTE || "";
    const IconComp = window.Icon;
    const { resolvedCases, resolvedBlogs } = resolveProof(caseSlugs, blogSlugs);

    if (!resolvedCases.length && !resolvedBlogs.length) return null;

    const inner = (
      <div className={embedded ? "sm-proof sm-proof-embedded" : "sm-proof"}>
        {!embedded && <SectionIntro eyebrow={eyebrow} heading={heading} intro={intro} />}
        {embedded && (heading || eyebrow) && (
          <div className="sm-proof-subhead">
            {eyebrow && <span className="overline-grad">{eyebrow}</span>}
            {heading && <h3 className="sm-proof-sub-title">{heading}</h3>}
          </div>
        )}
        <div className="sm-proof-grid">
          {resolvedCases.map((c) => (
            <a key={"case-" + c.slug} href={`/case-studies/${c.slug}`} className="sm-proof-card is-case">
              <div className="sm-proof-meta">
                <span className="sm-proof-badge is-case">Case Study</span>
                <span className="sm-proof-tag">{c.tag}</span>
              </div>
              <h4 className="sm-proof-title">{c.client}</h4>
              <p className="sm-proof-desc">{c.challenge}</p>
              {Array.isArray(c.metrics) && c.metrics.length > 0 && (
                <div className="sm-proof-metrics">
                  {c.metrics.slice(0, 3).map(([num, suf, lbl], idx) => (
                    <div key={idx} className="sm-proof-metric">
                      <span className="sm-proof-num gt">{num}{suf}</span>
                      <span className="sm-proof-lbl">{lbl}</span>
                    </div>
                  ))}
                </div>
              )}
              <span className="sm-proof-cta">
                Read the full case study {IconComp ? <IconComp name="arrow-right" size={15} /> : "→"}
              </span>
            </a>
          ))}

          {resolvedBlogs.map((p) => (
            <a key={"blog-" + p.slug} href={`/blog/${p.slug}`} className="sm-proof-card is-blog">
              <div className="sm-proof-meta">
                <span className="sm-proof-badge is-blog">{p.tag || "Playbook"}</span>
                {p.readTime && <span className="sm-proof-tag">{p.readTime}</span>}
              </div>
              <h4 className="sm-proof-title">{p.title}</h4>
              <p className="sm-proof-desc">{p.excerpt}</p>
              <span className="sm-proof-cta">
                Read the guide {IconComp ? <IconComp name="arrow-right" size={15} /> : "→"}
              </span>
            </a>
          ))}
        </div>
        {resolvedCases.length > 0 && repNote && (
          <p className="sm-proof-rep-note">{repNote}</p>
        )}
      </div>
    );

    if (embedded) return inner;
    return (
      <section className="sec sm-section">
        <div className="wrap-wide">{inner}</div>
      </section>
    );
  }

  /* ============================================================
     5. SpecialistProofStrip — Real Team + Quotes + Proof Grid
     ============================================================ */
  function SpecialistProofStrip({
    eyebrow = "Your senior team",
    heading = "The specialists actually inside your account.",
    intro,
    memberNames = [],
    quotes = {},
    caseSlugs = [],
    blogSlugs = []
  }) {
    const team = Array.isArray(window.TEAM) ? window.TEAM : [];
    const TeamPhotoComp = window.TeamPhoto;
    const requested = Array.isArray(memberNames) ? memberNames : [];
    const members = requested
      .map((name) => {
        const needle = String(name || "").toLowerCase();
        return team.find((m) => m.name.toLowerCase() === needle);
      })
      .filter(Boolean);

    const { resolvedCases, resolvedBlogs } = resolveProof(caseSlugs, blogSlugs);
    const hasProof = resolvedCases.length > 0 || resolvedBlogs.length > 0;
    if (!members.length && !hasProof) return null;

    return (
      <section className="sec sm-section">
        <div className="wrap-wide">
          <SectionIntro eyebrow={eyebrow} heading={heading} intro={intro} />
          {members.length > 0 && (
            <div className={"sm-spec-grid" + (members.length === 1 ? " is-single" : "")}>
              {members.map((m) => {
                const quote = quotes && (quotes[m.name] || quotes[m.photo]);
                return (
                  <article key={m.name} className="sm-spec-card">
                    <div className="sm-spec-photo">
                      {TeamPhotoComp ? (
                        <TeamPhotoComp photo={m.photo} alt={`${m.name}, ${m.role}`} width={320} height={400} />
                      ) : (
                        <img src={`assets/team/${m.photo}.png`} alt={`${m.name}, ${m.role}`} loading="lazy" decoding="async" />
                      )}
                    </div>
                    <div className="sm-spec-body">
                      <div className="sm-spec-role">{m.role}</div>
                      <h3 className="sm-spec-name">{m.name}</h3>
                      <p className="sm-spec-bio">{m.d}</p>
                      {quote && <blockquote className="sm-spec-quote">&ldquo;{quote}&rdquo;</blockquote>}
                    </div>
                  </article>
                );
              })}
            </div>
          )}
          {hasProof && (
            <RelatedProofGrid
              embedded
              eyebrow="Related proof & playbooks"
              heading="See the work and the method behind it."
              caseSlugs={caseSlugs}
              blogSlugs={blogSlugs}
            />
          )}
        </div>
      </section>
    );
  }

  /* ============================================================
     6. ServiceFaqSection — Accessible Native <details> Accordion
     ============================================================ */
  function ServiceFaqSection({
    eyebrow = "Frequently asked",
    heading = "Straight answers before we talk.",
    intro,
    faqs = [],
    ctaLabel,
    ctaHref = "/contact"
  }) {
    const safeFaqs = Array.isArray(faqs) ? faqs.filter((f) => f && f.q && f.a) : [];
    const [openMap, setOpenMap] = useSmState({ 0: true });
    const ButtonComp = window.Button;
    const IconComp = window.Icon;
    if (!safeFaqs.length) return null;

    const toggle = (idx) => {
      setOpenMap((prev) => ({ ...prev, [idx]: !prev[idx] }));
    };

    return (
      <section className="sec sm-section">
        <div className="wrap-wide">
          <div className="sm-faq-layout">
            <div className="sm-faq-side">
              <SectionIntro eyebrow={eyebrow} heading={heading} intro={intro} />
              {ctaLabel && (
                <div style={{ marginTop: 24 }}>
                  {ButtonComp ? (
                    <ButtonComp variant="secondary" icon="arrow-right" href={ctaHref}>{ctaLabel}</ButtonComp>
                  ) : (
                    <a href={ctaHref} className="btn btn-secondary">{ctaLabel}</a>
                  )}
                </div>
              )}
            </div>
            <div className="sm-faq">
              {safeFaqs.map((f, i) => {
                const isOpen = !!openMap[i];
                return (
                  <details key={i} className="sm-faq-item" open={isOpen}>
                    <summary
                      className="sm-faq-q"
                      onClick={(e) => {
                        e.preventDefault();
                        toggle(i);
                      }}
                    >
                      <span>{f.q}</span>
                      <span className={"sm-faq-icon" + (isOpen ? " is-open" : "")} aria-hidden="true">
                        {IconComp ? <IconComp name="plus" size={16} /> : "+"}
                      </span>
                    </summary>
                    <div className="sm-faq-a">{f.a}</div>
                  </details>
                );
              })}
            </div>
          </div>
        </div>
      </section>
    );
  }

  Object.assign(window, {
    ContrarianComparison,
    ChannelDiagnostic,
    QualificationSplit,
    SpecialistProofStrip,
    RelatedProofGrid,
    ServiceFaqSection
  });
})();
