import React, { useEffect, useRef } from 'react';
import type { EditorStore } from '../../store/editorStore';

type LayoutId = 'block1' | 'block2' | 'block3' | 'flex' | 'grid';

interface Props {
  store: EditorStore;
  afterSectionId?: string;
  onClose: () => void;
  direction?: 'up' | 'down';
  /** Ref to the trigger button — excluded from outside-click detection. */
  triggerRef?: React.RefObject<HTMLButtonElement>;
  /**
   * Opens the Template Library. Canvas passes this down; without it the
   * library has no entry point in the UI.
   */
  onOpenTemplates?: () => void;
}

const PRESETS: Array<{ id: LayoutId; label: string; icon: React.ReactNode }> = [
  {
    id: 'block1',
    label: 'Single Col',
    icon: (
      <svg width="40" height="26" viewBox="0 0 40 26" fill="none">
        <rect x="2" y="2" width="36" height="22" rx="3" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
      </svg>
    ),
  },
  {
    id: 'block2',
    label: '2 Columns',
    icon: (
      <svg width="40" height="26" viewBox="0 0 40 26" fill="none">
        <rect x="2"  y="2" width="16" height="22" rx="3" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
        <rect x="22" y="2" width="16" height="22" rx="3" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
      </svg>
    ),
  },
  {
    id: 'block3',
    label: '3 Columns',
    icon: (
      <svg width="40" height="26" viewBox="0 0 40 26" fill="none">
        <rect x="2"    y="2" width="10" height="22" rx="2.5" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
        <rect x="15"   y="2" width="10" height="22" rx="2.5" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
        <rect x="28"   y="2" width="10" height="22" rx="2.5" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
      </svg>
    ),
  },
  {
    id: 'flex',
    label: 'Flex Row',
    icon: (
      <svg width="40" height="26" viewBox="0 0 40 26" fill="none">
        <rect x="2" y="2" width="36" height="22" rx="3" fill="rgba(99,102,241,0.04)" stroke="rgba(99,102,241,0.3)" strokeWidth="1.5" strokeDasharray="3 2"/>
        <path d="M14 13h12M23 9l4 4-4 4" stroke="rgba(99,102,241,0.6)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    ),
  },
  {
    id: 'grid',
    label: 'Auto Grid',
    icon: (
      <svg width="40" height="26" viewBox="0 0 40 26" fill="none">
        <rect x="2"  y="2"  width="16" height="10" rx="2" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
        <rect x="22" y="2"  width="16" height="10" rx="2" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
        <rect x="2"  y="14" width="16" height="10" rx="2" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
        <rect x="22" y="14" width="16" height="10" rx="2" fill="rgba(99,102,241,0.1)" stroke="rgba(99,102,241,0.4)" strokeWidth="1.5"/>
      </svg>
    ),
  },
];

export function SectionPicker({ store, afterSectionId, onClose, triggerRef, direction = 'down', onOpenTemplates }: Props) {
  const rootRef = useRef<HTMLDivElement>(null);

  // Close on Escape or click outside (but not on the trigger itself)
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (triggerRef?.current?.contains(t)) return;
      if (rootRef.current && !rootRef.current.contains(t)) onClose();
    };
    document.addEventListener('keydown', onKey);
    document.addEventListener('mousedown', onDown);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.removeEventListener('mousedown', onDown);
    };
  }, [onClose, triggerRef]);

  const pick = (id: LayoutId) => {
    store.addSectionWithLayout(afterSectionId, id);
    onClose();
  };

  return (
    <div
      className={`jalpi-qadd${direction === 'up' ? ' jalpi-qadd--up' : ''}`}
      ref={rootRef}
      role="dialog"
      aria-label="Add section"
    >
      <div className="jalpi-qadd__heading">Choose a layout</div>

      <div className="jalpi-qadd__grid">
        {PRESETS.map((p) => (
          <button
            key={p.id}
            className="jalpi-qadd__card"
            onClick={() => pick(p.id)}
            title={p.label}
          >
            <span className="jalpi-qadd__card-preview">{p.icon}</span>
            <span className="jalpi-qadd__card-label">{p.label}</span>
          </button>
        ))}
      </div>

      {/* Entry point into the Template Library — start from a ready-made
          landing page or section instead of an empty layout. */}
      {onOpenTemplates && (
        <button
          type="button"
          className="jalpi-qadd__templates"
          onClick={() => { onClose(); onOpenTemplates(); }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
               strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <rect x="3" y="3" width="7" height="7" rx="1" /><rect x="14" y="3" width="7" height="7" rx="1" />
            <rect x="3" y="14" width="7" height="7" rx="1" /><rect x="14" y="14" width="7" height="7" rx="1" />
          </svg>
          Browse Templates
        </button>
      )}
    </div>
  );
}
