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);
  if (plain.length <= length) return plain;
  return `${plain.slice(0, length).trimEnd()}...`;
}

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

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

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

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

    async function load() {
      try {
        const [sectionRes, featureRes, readingRes] = await Promise.all([
          fetch("/api/sections.php?lang=en&slug=writing", { signal: controller.signal }),
          fetch("/api/pages.php?lang=en&slug=boris-vian-april-2026", { signal: controller.signal }),
          fetch("/api/pages.php?lang=en&slug=boris-vian-reading-route", { signal: controller.signal }),
        ]);

        if (!sectionRes.ok || !featureRes.ok || !readingRes.ok) {
          throw new Error("The CMS endpoints did not respond cleanly.");
        }

        const sectionJson = await sectionRes.json();
        const featureJson = await featureRes.json();
        const readingJson = await readingRes.json();
        const section = Array.isArray(sectionJson) ? sectionJson[0] : sectionJson;

        if (!section || !featureJson || !readingJson) {
          throw new Error("The writing issue payload was incomplete.");
        }

        setState({
          status: "ready",
          section,
          feature: featureJson,
          reading: readingJson,
          error: "",
        });
      } catch (error) {
        if (controller.signal.aborted) return;
        setState({
          status: "error",
          section: null,
          feature: null,
          reading: 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, feature, reading } = state;
  const leadArticles = Array.isArray(section.articles) ? section.articles : [];
  const featureArticle =
    leadArticles.find((article) => article.title === feature.title) ?? leadArticles[0] ?? null;
  const readingArticle =
    leadArticles.find((article) => article.title === reading.title) ?? leadArticles[1] ?? null;

  return (
    <div className="writing-live">
      <section className="container writing-live__hero">
        <div className="writing-live__copy">
          <span className="eyebrow">{section.headline}</span>
          <h1>{section.name}</h1>
          <div
            className="writing-live__lede"
            dangerouslySetInnerHTML={{ __html: section.homepage_html }}
          />

          <div className="writing-live__notes">
            <article className="panel writing-live__signal">
              <span>Lead feature</span>
              <strong>{feature.title}</strong>
              <p>{excerpt(feature.content, 210)}</p>
            </article>

            <article className="panel writing-live__signal">
              <span>Companion route</span>
              <strong>{reading.title}</strong>
              <p>{excerpt(reading.content, 180)}</p>
            </article>
          </div>
        </div>

        <aside className="panel writing-live__cover">
          {section.image_url && (
            <img src={section.image_url} alt={section.photo_description || section.name} loading="eager" />
          )}
          <div className="writing-live__cover-copy">
            <div className="capsule__kicker">
              <span>April file</span>
              <span>{feature.category_name || "Writing desk"}</span>
            </div>
            <h2>{feature.title}</h2>
            <p>{excerpt(feature.content, 240)}</p>
            {section.photo_credit && (
              <p className="writing-live__credit">Image credit: {section.photo_credit}</p>
            )}
          </div>
        </aside>
      </section>

      <section className="container writing-live__columns">
        <article className="panel writing-live__body">
          <div className="capsule__kicker">
            <span>Feature essay</span>
            <span>Boris / Vernon / jazz / Paris</span>
          </div>
          <div
            className="writing-live__rich"
            dangerouslySetInnerHTML={{ __html: feature.content }}
          />
        </article>

        <aside className="writing-live__side">
          <article className="panel writing-live__card">
            <div className="capsule__kicker">
              <span>Reading route</span>
              <span>Companion piece</span>
            </div>
            <div
              className="writing-live__rich writing-live__rich--compact"
              dangerouslySetInnerHTML={{ __html: reading.content }}
            />
          </article>

          <article className="panel writing-live__card">
            <div className="capsule__kicker">
              <span>What is live from the CMS</span>
              <span>{leadArticles.length} article{leadArticles.length === 1 ? "" : "s"}</span>
            </div>
            <ul className="writing-live__article-list">
              {leadArticles.map((article) => (
                <li key={article.id ?? article.title}>
                  <strong>{article.title}</strong>
                  <p>{excerpt(article.body, 150)}</p>
                </li>
              ))}
            </ul>
          </article>

          <article className="panel writing-live__card">
            <div className="capsule__kicker">
              <span>Editorial note</span>
              <span>Source-backed</span>
            </div>
            <p>
              This desk is now reading from the live PHP and SQL archive. Update the section intro,
              the Boris feature, the reading route, or the image credits in the CMS, and this page
              will follow.
            </p>
            {featureArticle?.published_at && (
              <p className="writing-live__meta">Feature published: {featureArticle.published_at}</p>
            )}
            {readingArticle?.published_at && (
              <p className="writing-live__meta">Reading route published: {readingArticle.published_at}</p>
            )}
          </article>
        </aside>
      </section>
    </div>
  );
}
