"use client";

import { useEffect, useState } from "react";
import { docSlugForType, docUrlForType } from "@/lib/componentDocMap";
import MarkdownDoc from "./MarkdownDoc";

type Lang = "FR" | "EN" | "ALL";

/**
 * Extract ## EN / ## FR sections from bilingual component docs.
 * Keeps tables and code fences intact (no aggressive trimming of structure).
 */
function extractLang(md: string, lang: Lang): string {
  if (lang === "ALL") return md;
  const title = titleFrom(md);
  const normalized = md.replace(/\r\n/g, "\n");

  const enIdx = normalized.search(/^## EN\s*$/m);
  const frIdx = normalized.search(/^## FR\s*$/m);

  if (lang === "EN" && enIdx >= 0) {
    const end = frIdx > enIdx ? frIdx : normalized.length;
    const body = normalized.slice(enIdx, end).replace(/^## EN\s*\n?/, "").trimEnd();
    return `# ${title}\n\n${body}\n`;
  }
  if (lang === "FR" && frIdx >= 0) {
    const body = normalized.slice(frIdx).replace(/^## FR\s*\n?/, "").trimEnd();
    return `# ${title}\n\n${body}\n`;
  }
  // Fallback: full document
  return md;
}

function titleFrom(md: string): string {
  const m = /^#\s+(.+)$/m.exec(md);
  return m ? m[1].trim() : "Documentation";
}

export default function ComponentDocPanel({
  componentType,
  fallbackHelp,
}: {
  componentType: string;
  fallbackHelp?: string;
}) {
  const [raw, setRaw] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [lang, setLang] = useState<Lang>("FR");

  const slug = docSlugForType(componentType);
  const url = docUrlForType(componentType);

  useEffect(() => {
    if (!url) {
      setRaw(null);
      setError(null);
      return;
    }
    let cancelled = false;
    setLoading(true);
    setError(null);
    fetch(url, { cache: "no-store" })
      .then(async (res) => {
        if (!res.ok) throw new Error(`Doc introuvable (${res.status})`);
        return res.text();
      })
      .then((text) => {
        if (!cancelled) {
          setRaw(text);
          setLoading(false);
        }
      })
      .catch((e: Error) => {
        if (!cancelled) {
          setRaw(null);
          setError(e.message);
          setLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
  }, [url]);

  if (!slug) {
    return (
      <div className="px-2.5 py-2 text-[10px] text-[var(--ink-faint)]">
        {fallbackHelp ? (
          <p className="whitespace-pre-line text-[var(--ink-dim)]">{fallbackHelp}</p>
        ) : (
          <p>Pas de fiche technique liée à ce type.</p>
        )}
      </div>
    );
  }

  return (
    <div className="flex max-h-[min(42vh,360px)] flex-col">
      <div className="flex items-center justify-end gap-1 border-b border-[var(--line)] bg-[var(--chrome-2)] px-2 py-1">
        {(["FR", "EN", "ALL"] as Lang[]).map((l) => (
          <button
            key={l}
            type="button"
            onClick={() => setLang(l)}
            className={`rounded px-1.5 py-0.5 text-[9px] font-semibold ${
              lang === l
                ? "bg-white text-[var(--ink)] shadow-sm"
                : "text-[var(--ink-faint)] hover:text-[var(--ink-dim)]"
            }`}
          >
            {l}
          </button>
        ))}
        {url && (
          <a
            href={url}
            target="_blank"
            rel="noreferrer"
            className="ml-1 text-[9px] text-[var(--accent)] underline"
            title="Ouvrir le fichier markdown"
          >
            .md
          </a>
        )}
      </div>
      <div className="min-h-0 flex-1 overflow-y-auto px-2.5 py-2">
        {loading && <p className="text-[10px] text-[var(--ink-faint)]">Chargement…</p>}
        {error && (
          <div className="text-[10px] text-[var(--hot)]">
            <p>{error}</p>
            {fallbackHelp && (
              <p className="mt-2 whitespace-pre-line text-[var(--ink-dim)]">{fallbackHelp}</p>
            )}
          </div>
        )}
        {!loading && !error && raw && <MarkdownDoc source={extractLang(raw, lang)} />}
      </div>
    </div>
  );
}
