/**
 * Supan Content — Gutenberg block editor sidebar plugin.
 *
 * Shows semantic link suggestions for the current post.
 * "Copy link" copies the HTML anchor tag — paste directly into Gutenberg.
 */

const { registerPlugin } = wp.plugins;
const { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editPost;
const { PanelBody, Button, Spinner } = wp.components;
const { useSelect } = wp.data;
const { useState } = wp.element;

interface Suggestion {
  slug: string;
  title: string;
  relevance: number;
  reason: string;
}

function SupanContentSidebar() {
  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [copied, setCopied] = useState<string | null>(null);

  const { postId } = useSelect((select) => {
    const editor = select('core/editor') as any;
    return {
      postId: editor.getCurrentPostId() as number,
    };
  });

  async function fetchSuggestions() {
    if (!postId) {
      setError('Save the post first to get suggestions.');
      return;
    }
    setLoading(true);
    setError('');
    setSuggestions([]);

    try {
      const res = await fetch(`${window.supacoCHBridge.restUrl}semantic-suggest`, {
        method: 'POST',
        headers: {
          'X-WP-Nonce': window.supacoCHBridge.nonce,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ post_id: postId }),
      });

      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        if (res.status === 429) {
          setError(err.reason || 'Monthly limit reached. Upgrade to continue.');
        } else {
          setError(err.message || `Error ${res.status}`);
        }
        return;
      }

      const data = await res.json();
      setSuggestions(data.suggestions || []);
    } catch {
      setError('Connection failed');
    } finally {
      setLoading(false);
    }
  }

  function copyLink(suggestion: Suggestion) {
    const linkHtml = `<a href="${window.location.origin}/${suggestion.slug}/">${suggestion.title}</a>`;
    navigator.clipboard.writeText(linkHtml).then(() => {
      setCopied(suggestion.slug);
      setTimeout(() => setCopied(null), 2000);
    });
  }

  return (
    <>
      <PluginSidebarMoreMenuItem target="supan-content-sidebar/supan-content-sidebar">
        Supan Content Links
      </PluginSidebarMoreMenuItem>
      <PluginSidebar name="supan-content-sidebar" title="Link Suggestions">
        <PanelBody>
          <Button
            variant="primary"
            onClick={fetchSuggestions}
            disabled={loading}
            style={{ width: '100%', justifyContent: 'center', marginBottom: 8 }}
          >
            {loading ? <Spinner /> : 'Find Link Suggestions'}
          </Button>

          {error && (
            <p style={{ fontSize: 12, color: '#EF4444', marginTop: 4 }}>{error}</p>
          )}

          {suggestions.length > 0 && (
            <div style={{ marginTop: 8 }}>
              <p style={{ fontSize: 11, color: '#6B7280', marginBottom: 8 }}>
                Click "Copy" then paste in the editor
              </p>
              {suggestions.map((s) => (
                <div
                  key={s.slug}
                  style={{
                    padding: '8px',
                    marginBottom: 6,
                    border: '1px solid #E5E7EB',
                    borderRadius: 4,
                    fontSize: 12,
                  }}
                >
                  <div style={{ fontWeight: 600, marginBottom: 4 }}>{s.title}</div>
                  <div style={{ color: '#6B7280', marginBottom: 6 }}>
                    Relevance: {Math.round(s.relevance * 100)}%
                  </div>
                  <Button
                    variant="secondary"
                    onClick={() => copyLink(s)}
                    style={{ fontSize: 11 }}
                  >
                    {copied === s.slug ? '✓ Copied!' : 'Copy link'}
                  </Button>
                </div>
              ))}
            </div>
          )}

          {!loading && suggestions.length === 0 && !error && (
            <p style={{ fontSize: 12, color: '#6B7280' }}>
              Click above to find semantically related posts to link from this one.
            </p>
          )}
        </PanelBody>
      </PluginSidebar>
    </>
  );
}

registerPlugin('supan-content-sidebar', { render: SupanContentSidebar });
