/**
 * ContainerHooksTab Component
 *
 * Documents PHP add_filter hooks for custom HTML/CSS/JS.
 * Shows element IDs for targeting and copyable hook snippets.
 */

import { CodeIcon, ExclamationTriangleIcon, InfoCircledIcon } from "@radix-ui/react-icons";

import { useCanvasStore, useElements } from "@/stores/canvasStore";
import { useLayoutPersistStore } from "@/stores/layoutPersistStore";
import {
  getPresetDefinition,
  presetHasCustomCode,
  presetOverridesCanvasStyles,
  type PresetCustomCode,
} from "@/registry/presetRegistry";
import { CopyButton } from "../ui/CopyButton";
import { generateAllLayoutHookSnippets, generateCombinedHookSnippet } from "@/utils/hookSnippets";

interface ContainerHooksTabProps {
  compact?: boolean;
}

function formatCustomCodeList(types: string[]): string {
  if (types.length <= 1) return types[0] ?? "";
  if (types.length === 2) return `${types[0]} and ${types[1]}`;
  return `${types.slice(0, -1).join(", ")}, and ${types[types.length - 1]}`;
}

function formatCustomCodeTypes(customCode: PresetCustomCode): string[] {
  const types: string[] = [];
  if (customCode.css) types.push("Custom CSS");
  if (customCode.html) types.push("Custom HTML");
  if (customCode.js) types.push("Custom JavaScript");
  return types;
}

export function ContainerHooksTab({ compact = true }: ContainerHooksTabProps) {
  const elements = useElements();
  const presetId = useCanvasStore((state) => state.presetId);
  const currentLayoutId = useLayoutPersistStore((state) => state.currentLayoutId);
  const preset = presetId ? getPresetDefinition(presetId) : undefined;
  const customCode = preset?.customCode;
  const hasPresetCustomCode = presetHasCustomCode(customCode);
  const overridesCanvasStyles = presetOverridesCanvasStyles(customCode);

  const sectionClass = compact ? "floating-settings__section floating-settings__section--scrollable" : "settings-section";
  const groupClass = compact ? "floating-settings__group" : "settings-group";
  const labelClass = compact ? "floating-settings__label" : "settings-label";
  const hintClass = compact ? "floating-settings__hint" : "settings-hint";

  const snippets = generateAllLayoutHookSnippets(currentLayoutId);
  const combinedSnippet = generateCombinedHookSnippet(currentLayoutId);

  const hookSections = [
    {
      type: "html" as const,
      title: "Custom HTML",
      hook: "oppb_layout_html",
      description: "Replace or modify the exported HTML template for this layout.",
      snippet: snippets.html,
    },
    {
      type: "css" as const,
      title: "Custom CSS",
      hook: "oppb_layout_css",
      description: "Append or modify CSS rules scoped to this layout.",
      snippet: snippets.css,
    },
    {
      type: "js" as const,
      title: "Custom JavaScript",
      hook: "oppb_layout_js",
      description: "Add JavaScript executed per layout container on the frontend.",
      snippet: snippets.js,
    },
  ];

  return (
    <div className={sectionClass}>
      <div className={groupClass}>
        <label className={`${labelClass} !flex items-center gap-2`}>
          <CodeIcon className="w-4 h-4" />
          Custom Code via Hooks
        </label>
        <p className={hintClass}>
          Add custom HTML, CSS, or JavaScript using WordPress filters in your theme&apos;s <code>functions.php</code> or a
          custom plugin. Code is never stored in the database.
        </p>
        {currentLayoutId ? (
          <p className={hintClass}>
            Current layout ID: <strong className="oppb-element-id-badge">#{currentLayoutId}</strong>
          </p>
        ) : (
          <p className={hintClass}>
            Save this layout first to get its ID. Snippets use <code>YOUR_LAYOUT_ID</code> until then.
          </p>
        )}
      </div>

      {hasPresetCustomCode && preset && customCode && (
        <div className={groupClass}>
          <label className={`${labelClass} !flex items-center gap-2`}>
            <InfoCircledIcon className="w-4 h-4" />
            Preset Bundled Code
          </label>
          <div className="oppb-hooks-preset-notice">
            <p className="oppb-hooks-preset-notice__text">
              This layout uses the <strong>{preset.name}</strong> preset, which ships with bundled{" "}
              {formatCustomCodeList(formatCustomCodeTypes(customCode))}.
            </p>
            {overridesCanvasStyles && (
              <p className="oppb-hooks-preset-notice__warning">
                <ExclamationTriangleIcon className="w-3.5 h-3.5 shrink-0" />
                <span>
                  Styles configured in the canvas editor will not be applied on the frontend. The preset&apos;s bundled
                  {customCode.html && customCode.css
                    ? " HTML and CSS"
                    : customCode.html
                      ? " HTML"
                      : " CSS"}{" "}
                  controls the appearance instead.
                </span>
              </p>
            )}
            {customCode.js && !overridesCanvasStyles && (
              <p className={hintClass}>
                The preset includes JavaScript for animations. Canvas styles still apply; only runtime behavior is
                enhanced.
              </p>
            )}
          </div>
        </div>
      )}

      {/* Element IDs */}
      {elements.length > 0 && (
        <div className={groupClass}>
          <label className={labelClass}>Element IDs</label>
          <p className={hintClass}>Use these IDs to target specific elements in your hook callbacks via CSS selectors or DOM queries.</p>
          <ul className="oppb-hooks-element-list">
            {elements.map((el) => (
              <li key={el.id} className="oppb-hooks-element-item">
                <code className="oppb-element-id-badge" data-element-id={el.id}>
                  {el.id}
                </code>
                <span className="oppb-hooks-element-meta">
                  {el.name} · {el.type}
                </span>
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Hook sections */}
      {hookSections.map((section) => (
        <div key={section.type} className={groupClass}>
          <div className="flex items-center justify-between gap-2">
            <label className={labelClass}>{section.title}</label>
            <CopyButton text={section.snippet} label="Copy" />
          </div>
          <p className={hintClass}>
            Filter: <code>{section.hook}</code> — {section.description}
          </p>
          <pre className="oppb-hooks-snippet">
            <code>{section.snippet}</code>
          </pre>
        </div>
      ))}

      <div className={groupClass}>
        <div className="flex items-center justify-between gap-2">
          <label className={labelClass}>All Hooks Combined</label>
          <CopyButton text={combinedSnippet} label="Copy all" />
        </div>
        <pre className="oppb-hooks-snippet oppb-hooks-snippet--combined">
          <code>{combinedSnippet}</code>
        </pre>
      </div>
    </div>
  );
}

export default ContainerHooksTab;
