// Use-case pages — the /use-cases/ hub and the ten pages beneath it.
//
// There is no body copy in this file on purpose. Every word lives in usecases-content.php,
// which renders the pages server-side AND emits them as window.AM_USECASES for this component
// — the same arrangement pages/legal.jsx uses, and for a stronger reason: these pages exist to
// be found in a search, so the server-rendered copy is the one that gets indexed. If the text
// were written twice the indexed version and the read version would drift, and the drift would
// be invisible to anyone testing in a browser.
//
// Keep the sections here in step with AM_usecaseHTML() in usecases-content.php. A visitor
// should not be able to tell whether they got the PHP render or this one.

const { useState: useStateUC, useEffect: useEffectUC } = React;

function UcCheck() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" aria-hidden="true">
      <path d="M5 13l4 4L19 7"/>
    </svg>
  );
}

function UcParts({ parts }) {
  return (
    <div className="uc-parts">
      <span className="uc-parts-label">Built from</span>
      <div className="uc-parts-list">
        {parts.map(p => <span key={p} className="uc-part">{p}</span>)}
      </div>
    </div>
  );
}

// Breadcrumbs are real <a href> links as well as SPA navigations — they are mirrored in the
// BreadcrumbList structured data index.php emits, and a crumb a crawler cannot follow is worse
// than no crumb at all.
function UcCrumbs({ current, onNavigate, onNavigateUseCase }) {
  return (
    <nav className="ucp-crumbs" aria-label="Breadcrumb">
      <a href="/" onClick={spaClick(() => onNavigate("home"))}>Home</a>
      <span aria-hidden="true">/</span>
      {current ? (
        <React.Fragment>
          <a href="/use-cases/" onClick={spaClick(() => onNavigateUseCase(null))}>Use cases</a>
          <span aria-hidden="true">/</span>
          <span>{current}</span>
        </React.Fragment>
      ) : <span>Use cases</span>}
    </nav>
  );
}

/* =============================================================================
   DETAIL — one use case
   ============================================================================= */

function UseCaseDetailPage({ uc, slug, all, onNavigate, onNavigateUseCase }) {
  return (
    <div className="page ucp">

      <section className="ucp-hero">
        <div className="container">
          <UcCrumbs current={uc.nav} onNavigate={onNavigate} onNavigateUseCase={onNavigateUseCase} />
          <span className="uc-tag solid">{uc.tag}</span>
          <h1>{uc.h1}</h1>
          <p className="lead">{uc.intro}</p>
          <blockquote className="ucp-said">{uc.said}</blockquote>
          <div className="ucp-hero-cta">
            <a href="/contact/" className="btn btn-primary" onClick={spaClick(() => onNavigate("contact"))}>
              Talk about this one
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            </a>
            <a href="/platform/" className="btn btn-ghost" onClick={spaClick(() => onNavigate("platform"))}>See the platform</a>
          </div>
        </div>
      </section>

      <section className="ucp-symptoms">
        <div className="container">
          <h2>You are probably here because</h2>
          <ul className="ucp-symptom-list">
            {uc.symptoms.map((s, i) => <li key={i}>{s}</li>)}
          </ul>
        </div>
      </section>

      <section className="ucp-prose">
        <div className="container">
          <div className="ucp-prose-grid">
            <div className="ucp-prose-col">
              <h2>What is actually going wrong</h2>
              {uc.wrong.map((p, i) => <p key={i}>{p}</p>)}
            </div>
            <div className="ucp-prose-col">
              <h2>What we build</h2>
              {uc.build.map((p, i) => <p key={i}>{p}</p>)}
            </div>
          </div>
        </div>
      </section>

      <section className="ucp-steps">
        <div className="container">
          <h2>How it goes together</h2>
          <ol className="ucp-step-list">
            {uc.steps.map(s => (
              <li className="ucp-step" key={s.n}>
                <span className="ucp-step-n mono">{s.n}</span>
                <div className="ucp-step-body">
                  <h3>{s.h}</h3>
                  <p>{s.p}</p>
                  <UcParts parts={s.parts} />
                </div>
              </li>
            ))}
          </ol>
        </div>
      </section>

      <section className="ucp-partstable">
        <div className="container">
          <h2>The platform features doing the work</h2>
          <p className="lead">
            Nothing here is written specially for this use case — it is the same platform every
            ActiveManage application is built from.{" "}
            <a href="/platform/" onClick={spaClick(() => onNavigate("platform"))}>The full feature list is on the platform page.</a>
          </p>
          <div className="ucp-table-wrap">
            <table className="ucp-table">
              <thead>
                <tr><th>Feature</th><th>What it does</th><th>Why it matters here</th></tr>
              </thead>
              <tbody>
                {uc.parts.map(p => (
                  <tr key={p.name}>
                    <th scope="row">{p.name}</th>
                    <td>{p.what}</td>
                    <td>{p.why}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </section>

      <section className="ucp-proof">
        <div className="container">
          <h2>What you end up with</h2>
          <ul className="uc-proof">
            {uc.proof.map((p, i) => <li key={i}><UcCheck />{p}</li>)}
          </ul>
        </div>
      </section>

      <section className="ucp-fit">
        <div className="container">
          <h2>Whether this is for you</h2>
          <div className="ucp-fit-grid">
            <div className="ucp-fit-col is-for">
              <h3>A good fit when</h3>
              <ul>{uc.fit.for.map((f, i) => <li key={i}>{f}</li>)}</ul>
            </div>
            <div className="ucp-fit-col is-not">
              <h3>Probably not, if</h3>
              <ul>{uc.fit.not.map((f, i) => <li key={i}>{f}</li>)}</ul>
            </div>
          </div>
        </div>
      </section>

      <section className="ucp-shape">
        <div className="container">
          <h2>How a project like this runs</h2>
          <div className="ucp-shape-grid">
            {uc.shape.map(s => (
              <div className="ucp-shape-item" key={s.h}>
                <h3>{s.h}</h3>
                <p>{s.p}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="ucp-faqs">
        <div className="container">
          <h2>Questions we get asked</h2>
          <div className="ucp-faq-list">
            {uc.faqs.map((f, i) => (
              <div className="ucp-faq" key={i}>
                <h3>{f.q}</h3>
                <p>{f.a}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {uc.related && uc.related.length > 0 && (
        <section className="ucp-related">
          <div className="container">
            <h2>Related use cases</h2>
            <div className="ucp-related-grid">
              {uc.related.filter(r => all[r]).map(r => (
                <a
                  key={r}
                  className="ucp-related-card"
                  href={"/use-cases/" + r + "/"}
                  onClick={spaClick(() => onNavigateUseCase(r))}
                >
                  <span className="uc-tag">{all[r].tag}</span>
                  <span className="ucp-related-said">{all[r].said}</span>
                  <span className="ucp-related-go">Read more <span aria-hidden="true">→</span></span>
                </a>
              ))}
            </div>
            <p className="ucp-related-all">
              <a href="/use-cases/" onClick={spaClick(() => onNavigateUseCase(null))}>All use cases</a>
            </p>
          </div>
        </section>
      )}

      <section className="ucp-cta">
        <div className="container">
          <h2>Sound like your week?</h2>
          <p>Tell us what you are trying to fix and we will tell you whether this is the right shape for it — including when it is not.</p>
          <div className="ucp-hero-cta">
            <a href="/contact/" className="btn btn-accent" onClick={spaClick(() => onNavigate("contact"))}>
              Start a conversation
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            </a>
            <a href="/bespoke/" className="btn btn-ghost" onClick={spaClick(() => onNavigate("bespoke"))}>How we work</a>
          </div>
        </div>
      </section>

    </div>
  );
}

/* =============================================================================
   HUB — /use-cases/
   ============================================================================= */

// The heading and intro are duplicated from the 'usecases' entry in routes.php, which is what
// the server renders. That duplication is the standing cost of prerendering without a build
// step (see the header of routes.php) — if you change the wording, change it in both places.
function UseCaseIndexPage({ all, onNavigate, onNavigateUseCase }) {
  return (
    <div className="page ucp ucp-index">

      <section className="ucp-hero">
        <div className="container">
          <UcCrumbs onNavigate={onNavigate} onNavigateUseCase={onNavigateUseCase} />
          <span className="eyebrow">Where it fits</span>
          <h1>What people actually build with us</h1>
          <p className="lead">
            Nobody goes shopping for a development platform. They go looking for a fix to
            something specific that is costing them time, money or sleep. These are the ten
            problems we are asked about most often, each written up properly: what tends to be
            going wrong, what we build instead, which parts of the platform do the work, and —
            because it saves everyone time — when you would be better off with something else.
          </p>
        </div>
      </section>

      <section className="ucp-index-list">
        <div className="container">
          <div className="ucp-index-grid">
            {Object.keys(all).map(slug => {
              const uc = all[slug];
              return (
                <a
                  key={slug}
                  className="ucp-index-card"
                  href={"/use-cases/" + slug + "/"}
                  onClick={spaClick(() => onNavigateUseCase(slug))}
                >
                  <span className="uc-tag">{uc.tag}</span>
                  <h2>{uc.said}</h2>
                  <p>{uc.intro}</p>
                  <span className="ucp-related-go">{uc.nav} <span aria-hidden="true">→</span></span>
                </a>
              );
            })}
          </div>
        </div>
      </section>

      <section className="ucp-cta">
        <div className="container">
          <h2>Not on the list?</h2>
          <p>
            These are the ten we are asked for most often, not the limit of what the platform
            builds. If your problem is not here, describe it to us in plain English and we will
            tell you honestly whether it fits.
          </p>
          <div className="ucp-hero-cta">
            <a href="/contact/" className="btn btn-accent" onClick={spaClick(() => onNavigate("contact"))}>
              Describe your problem
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            </a>
            <a href="/platform/" className="btn btn-ghost" onClick={spaClick(() => onNavigate("platform"))}>See the platform</a>
          </div>
        </div>
      </section>

    </div>
  );
}

/* =============================================================================
   SHELL — picks hub or detail, and sources the payload
   ============================================================================= */

// index.php inlines two payloads on a use-case route, and neither anywhere else:
//
//   window.AM_USECASES_INDEX  all ten, four fields each — enough for every card
//   window.AM_USECASES        the one document being viewed, in full
//
// So a direct hit on /use-cases/crm/ re-renders with no fetch and no flash, which is the load
// that matters, because it is the one arriving from a search result. Anything else — reaching
// a use case by clicking through from the homepage, or moving between two of them without a
// reload — finds what it needs missing and fetches the full set once, cached back onto window.
//
// Fetching is therefore the uncommon path, and it is the only one that ever shows a skeleton.
function UseCasesPage({ slug, onNavigate, onNavigateUseCase }) {
  const [all, setAll] = useStateUC(() => (typeof window !== "undefined" ? window.AM_USECASES : null) || null);
  const [index, setIndex] = useStateUC(() => (typeof window !== "undefined" ? window.AM_USECASES_INDEX : null) || null);
  const [failed, setFailed] = useStateUC(false);

  // The hub only needs the index; a detail page needs its own full document. Asking for
  // exactly what this render requires is what keeps the common case free of a round trip.
  const hasIndex = !!(index && Object.keys(index).length);
  const needsFetch = slug ? !(all && all[slug]) : !hasIndex;

  useEffectUC(() => {
    if (!needsFetch || failed) return;
    let alive = true;
    fetch("/usecases-data.php", { headers: { Accept: "application/json" } })
      .then(r => (r.ok ? r.json() : Promise.reject(r.status)))
      .then(j => {
        if (!alive) return;
        if (j && typeof j === "object" && Object.keys(j).length) {
          // The full set supersedes the partial payload for both purposes — it is a superset
          // of the index, so derive the index from it rather than keeping two sources.
          window.AM_USECASES = j;
          setAll(j);
          setIndex(j);
        } else {
          setFailed(true);
        }
      })
      .catch(() => { if (alive) setFailed(true); });
    return () => { alive = false; };
  }, [needsFetch, failed]);

  if (needsFetch && !failed) {
    return (
      <div className="page ucp">
        <div className="container">
          <div className="docs-skeleton">
            <div className="sk sk-h1"></div>
            <div className="sk sk-lead"></div>
            <div className="sk sk-p"></div><div className="sk sk-p"></div><div className="sk sk-p short"></div>
          </div>
        </div>
      </div>
    );
  }

  // Genuinely unavailable — the fetch failed too. Say so, and still offer a way forward,
  // rather than rendering an empty page that looks like the content.
  if (needsFetch) {
    return (
      <div className="page ucp">
        <div className="container" style={{ paddingBlock: 80 }}>
          <h1>Use cases</h1>
          <p className="lead">
            We couldn't load this page. Please reload, or{" "}
            <a href="/contact/" onClick={spaClick(() => onNavigate("contact"))}>tell us what you're trying to fix</a>{" "}
            and we'll answer directly.
          </p>
        </div>
      </div>
    );
  }

  const uc = slug && all ? all[slug] : null;

  // A slug nothing knows about. The server 404s these before React ever loads, so this only
  // happens if the route table and the content file have drifted — fall back to the hub rather
  // than a blank page.
  if (slug && !uc) {
    return <UseCaseIndexPage all={index || {}} onNavigate={onNavigate} onNavigateUseCase={onNavigateUseCase} />;
  }

  // `index` rather than `all` for the cards: it is always present and always sufficient, where
  // the full set is only loaded when something actually needed it.
  return uc
    ? <UseCaseDetailPage uc={uc} slug={slug} all={index || {}} onNavigate={onNavigate} onNavigateUseCase={onNavigateUseCase} />
    : <UseCaseIndexPage all={index || {}} onNavigate={onNavigate} onNavigateUseCase={onNavigateUseCase} />;
}

Object.assign(window, { UseCasesPage, UseCaseDetailPage, UseCaseIndexPage });
