import { useEffect, useState } from "react";

function stripHtml(html) {
  return html
    .replace(/<style[\s\S]*?<\/style>/gi, "")
    .replace(/<script[\s\S]*?<\/script>/gi, "")
    .replace(/<[^>]+>/g, " ")
    .replace(/&nbsp;/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function excerpt(html, length = 220) {
  const plain = stripHtml(html);
  return plain.length <= length ? plain : `${plain.slice(0, length).trimEnd()}...`;
}

function LoadingBlock() {
  return (
    <section className="business-live__loading panel">
      <div className="capsule__kicker">
        <span>Business desk</span>
        <span>Fetching live file</span>
      </div>
      <h2>Loading the April business issue...</h2>
      <p>The public business desk is pulling its copy from the live PHP archive.</p>
    </section>
  );
}

function ErrorBlock({ message }) {
  return (
    <section className="business-live__loading panel">
      <div className="capsule__kicker">
        <span>Business desk</span>
        <span>Archive offline</span>
      </div>
      <h2>The business issue could not be loaded.</h2>
      <p>{message}</p>
    </section>
  );
}

export default function BusinessIssue() {
  const [state, setState] = useState({
    status: "loading",
    section: null,
    error: "",
  });

  useEffect(() => {
    const controller = new AbortController();

    async function load() {
      try {
        const response = await fetch("/api/sections.php?lang=en&slug=business", {
          signal: controller.signal,
        });
        if (!response.ok) throw new Error("The CMS endpoint did not respond cleanly.");
        const json = await response.json();
        const section = Array.isArray(json) ? json[0] : json;
        if (!section) throw new Error("The business desk payload was empty.");
        setState({ status: "ready", section, error: "" });
      } catch (error) {
        if (controller.signal.aborted) return;
        setState({
          status: "error",
          section: null,
          error: error instanceof Error ? error.message : "Unknown loading error.",
        });
      }
    }

    load();
    return () => controller.abort();
  }, []);

  if (state.status === "loading") return <LoadingBlock />;
  if (state.status === "error") return <ErrorBlock message={state.error} />;

  const { section } = state;
  const articles = Array.isArray(section.articles) ? section.articles : [];
  const feature =
    articles.find((article) => article.title.startsWith("April Feature")) ?? articles[0] ?? null;
  const memo =
    articles.find((article) => article.title.startsWith("Companion Memo")) ?? articles[1] ?? null;

  return (
    <div className="business-live">
      <section className="container business-live__hero">
        <div className="business-live__copy">
          <span className="eyebrow">{section.headline}</span>
          <h1>{section.name}</h1>
          <div
            className="business-live__lede"
            dangerouslySetInnerHTML={{ __html: section.homepage_html }}
          />
          {feature && (
            <div className="business-live__signals">
              <article className="panel business-live__signal">
                <span>Lead file</span>
                <strong>{feature.title}</strong>
                <p>{excerpt(feature.body, 210)}</p>
              </article>
              {memo && (
                <article className="panel business-live__signal">
                  <span>Companion memo</span>
                  <strong>{memo.title}</strong>
                  <p>{excerpt(memo.body, 170)}</p>
                </article>
              )}
            </div>
          )}
        </div>

        <aside className="panel business-live__cover">
          {section.image_url && (
            <img
              src={section.image_url}
              alt={section.photo_description || section.name}
              loading="eager"
            />
          )}
          <div className="business-live__cover-copy">
            <div className="capsule__kicker">
              <span>April issue</span>
              <span>AI x labour x pataphysics</span>
            </div>
            <h2>The science of imaginary co-workers.</h2>
            <p>{excerpt(section.page_html, 220)}</p>
            {section.photo_credit && (
              <p className="business-live__credit">Image credit: {section.photo_credit}</p>
            )}
          </div>
        </aside>
      </section>

      <section className="container business-live__columns">
        <article className="panel business-live__feature">
          <div className="capsule__kicker">
            <span>Feature essay</span>
            <span>Agents / labour / Queneau / Ionesco / Pr&eacute;vert</span>
          </div>
          {feature ? (
            <div
              className="business-live__rich"
              dangerouslySetInnerHTML={{ __html: feature.body }}
            />
          ) : (
            <p>No feature article is available yet.</p>
          )}
        </article>

        <aside className="business-live__side">
          {memo && (
            <article className="panel business-live__card">
              <div className="capsule__kicker">
                <span>Companion memo</span>
                <span>Three tests</span>
              </div>
              <div
                className="business-live__rich business-live__rich--compact"
                dangerouslySetInnerHTML={{ __html: memo.body }}
              />
            </article>
          )}

          <article className="panel business-live__card">
            <div className="capsule__kicker">
              <span>Live from the CMS</span>
              <span>{articles.length} article{articles.length === 1 ? "" : "s"}</span>
            </div>
            <ul className="business-live__article-list">
              {articles.map((article) => (
                <li key={article.id ?? article.title}>
                  <strong>{article.title}</strong>
                  <p>{excerpt(article.body, 140)}</p>
                </li>
              ))}
            </ul>
          </article>

          <article className="panel business-live__card">
            <div className="capsule__kicker">
              <span>Editorial note</span>
              <span>Fake quotes, real sources</span>
            </div>
            <p>
              The invented quotations are marked as invented. The adoption, labour, and pataphysical
              framing are anchored to cited OECD, WEF, and Coll&egrave;ge sources.
            </p>
            {feature?.published_at && (
              <p className="business-live__meta">Feature published: {feature.published_at}</p>
            )}
            {memo?.published_at && (
              <p className="business-live__meta">Memo published: {memo.published_at}</p>
            )}
          </article>
        </aside>
      </section>
    </div>
  );
}
