/**
 * ProRank SEO FAQ Schema Block
 *
 * Simple FAQ block that outputs FAQPage JSON-LD.
 */

import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';
import { Button, TextControl, TextareaControl } from '@wordpress/components';

const FaqIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path
      fill="currentColor"
      d="M12 2C6.48 2 2 6.48 2 12c0 1.85.5 3.58 1.37 5.06L2 22l4.94-1.37A9.96 9.96 0 0 0 12 22c5.52 0 10-4.48 10-10S17.52 2 12 2zm.75 15h-1.5v-1.5h1.5V17zm1.55-5.8-.68.7c-.55.56-.87 1.02-.87 2.1h-1.5v-.38c0-.84.32-1.62.87-2.18l.93-.95a1.9 1.9 0 0 0 .55-1.34c0-1.07-.87-1.95-1.95-1.95s-1.95.88-1.95 1.95H8.2a3.45 3.45 0 0 1 6.9 0c0 .9-.36 1.75-.8 2.05z"
    />
  </svg>
);

const normalizeItems = (items) => {
  if (!Array.isArray(items) || items.length === 0) {
    return [{ question: '', answer: '' }];
  }

  return items.map((item) => ({
    question: typeof item?.question === 'string' ? item.question : '',
    answer: typeof item?.answer === 'string' ? item.answer : '',
  }));
};

const Edit = ({ attributes, setAttributes }) => {
  const blockProps = useBlockProps({ className: 'prorank-faq-schema-block-editor' });
  const title = typeof attributes.title === 'string' ? attributes.title : '';
  const items = normalizeItems(attributes.items);

  const updateItem = (index, key, value) => {
    const next = [...items];
    next[index] = { ...next[index], [key]: value };
    setAttributes({ items: next });
  };

  const addItem = () => {
    setAttributes({ items: [...items, { question: '', answer: '' }] });
  };

  const removeItem = (index) => {
    if (items.length <= 1) {
      setAttributes({ items: [{ question: '', answer: '' }] });
      return;
    }

    setAttributes({ items: items.filter((_, idx) => idx !== index) });
  };

  return (
    <div {...blockProps}>
      <div className="pr:space-y-4 pr:p-4 pr:border pr:border-gray-200 pr:rounded-lg pr:bg-white">
        <TextControl
          label={__('Block title (optional)', 'prorank-seo')}
          value={title}
          onChange={(value) => setAttributes({ title: value })}
          placeholder={__('Frequently Asked Questions', 'prorank-seo')}
        />

        {items.map((item, index) => (
          <div key={`faq-item-${index}`} className="pr:p-3 pr:border pr:border-gray-200 pr:rounded-md pr:space-y-3">
            <TextControl
              label={__('Question', 'prorank-seo')}
              value={item.question}
              onChange={(value) => updateItem(index, 'question', value)}
              placeholder={__('What is ProRank SEO?', 'prorank-seo')}
            />
            <TextareaControl
              label={__('Answer', 'prorank-seo')}
              value={item.answer}
              onChange={(value) => updateItem(index, 'answer', value)}
              placeholder={__('ProRank SEO is an all-in-one WordPress SEO plugin…', 'prorank-seo')}
              rows={4}
            />
            <Button variant="secondary" onClick={() => removeItem(index)}>
              {__('Remove question', 'prorank-seo')}
            </Button>
          </div>
        ))}

        <Button variant="primary" onClick={addItem}>
          {__('Add question', 'prorank-seo')}
        </Button>
      </div>
    </div>
  );
};

registerBlockType('prorank-seo/faq-schema', {
  apiVersion: 3,
  title: __('ProRank FAQ Schema', 'prorank-seo'),
  description: __('Build FAQ content and output FAQPage schema markup.', 'prorank-seo'),
  category: 'prorank-seo',
  icon: FaqIcon,
  keywords: [
    __('faq', 'prorank-seo'),
    __('schema', 'prorank-seo'),
    __('rich results', 'prorank-seo'),
  ],
  supports: {
    html: false,
  },
  attributes: {
    title: {
      type: 'string',
      default: '',
    },
    items: {
      type: 'array',
      default: [{ question: '', answer: '' }],
    },
    className: {
      type: 'string',
      default: '',
    },
  },
  edit: Edit,
  save: () => null,
});
