/**
 * ProRank SEO HowTo Schema Block
 *
 * Simple HowTo block that outputs HowTo 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 HowToIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
    <path
      fill="currentColor"
      d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 14H7v-2h3v2zm7-4H7v-2h10v2zm0-4H7V7h10v2z"
    />
  </svg>
);

const normalizeSteps = (steps) => {
  if (!Array.isArray(steps) || steps.length === 0) {
    return [{ title: '', text: '' }];
  }

  return steps.map((step) => ({
    title: typeof step?.title === 'string' ? step.title : '',
    text: typeof step?.text === 'string' ? step.text : '',
  }));
};

const Edit = ({ attributes, setAttributes }) => {
  const blockProps = useBlockProps({ className: 'prorank-howto-schema-block-editor' });
  const steps = normalizeSteps(attributes.steps);

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

  const addStep = () => {
    setAttributes({ steps: [...steps, { title: '', text: '' }] });
  };

  const removeStep = (index) => {
    if (steps.length <= 1) {
      setAttributes({ steps: [{ title: '', text: '' }] });
      return;
    }
    setAttributes({ steps: steps.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={__('HowTo title', 'prorank-seo')}
          value={attributes.title || ''}
          onChange={(value) => setAttributes({ title: value })}
          placeholder={__('How to optimize WordPress SEO', 'prorank-seo')}
        />

        <TextareaControl
          label={__('Description (optional)', 'prorank-seo')}
          value={attributes.description || ''}
          onChange={(value) => setAttributes({ description: value })}
          rows={3}
        />

        <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-3 pr:gap-3">
          <TextControl
            label={__('Total time (ISO 8601, optional)', 'prorank-seo')}
            value={attributes.totalTime || ''}
            onChange={(value) => setAttributes({ totalTime: value })}
            placeholder="PT30M"
          />
          <TextControl
            label={__('Estimated cost (optional)', 'prorank-seo')}
            value={attributes.estimatedCost || ''}
            onChange={(value) => setAttributes({ estimatedCost: value })}
            placeholder="49.00"
          />
          <TextControl
            label={__('Cost currency', 'prorank-seo')}
            value={attributes.estimatedCostCurrency || 'USD'}
            onChange={(value) => setAttributes({ estimatedCostCurrency: value })}
            placeholder="USD"
          />
        </div>

        <TextareaControl
          label={__('Tools (one per line, optional)', 'prorank-seo')}
          value={attributes.tools || ''}
          onChange={(value) => setAttributes({ tools: value })}
          rows={2}
        />

        <TextareaControl
          label={__('Supplies (one per line, optional)', 'prorank-seo')}
          value={attributes.supplies || ''}
          onChange={(value) => setAttributes({ supplies: value })}
          rows={2}
        />

        {steps.map((step, index) => (
          <div key={`howto-step-${index}`} className="pr:p-3 pr:border pr:border-gray-200 pr:rounded-md pr:space-y-3">
            <TextControl
              label={__('Step title', 'prorank-seo')}
              value={step.title}
              onChange={(value) => updateStep(index, 'title', value)}
              placeholder={__('Step 1', 'prorank-seo')}
            />
            <TextareaControl
              label={__('Step instruction', 'prorank-seo')}
              value={step.text}
              onChange={(value) => updateStep(index, 'text', value)}
              rows={3}
            />
            <Button variant="secondary" onClick={() => removeStep(index)}>
              {__('Remove step', 'prorank-seo')}
            </Button>
          </div>
        ))}

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

registerBlockType('prorank-seo/howto-schema', {
  apiVersion: 3,
  title: __('ProRank HowTo Schema', 'prorank-seo'),
  description: __('Build step-by-step instructions with HowTo schema markup.', 'prorank-seo'),
  category: 'prorank-seo',
  icon: HowToIcon,
  keywords: [
    __('howto', 'prorank-seo'),
    __('schema', 'prorank-seo'),
    __('rich results', 'prorank-seo'),
  ],
  supports: {
    html: false,
  },
  attributes: {
    title: {
      type: 'string',
      default: '',
    },
    description: {
      type: 'string',
      default: '',
    },
    totalTime: {
      type: 'string',
      default: '',
    },
    estimatedCost: {
      type: 'string',
      default: '',
    },
    estimatedCostCurrency: {
      type: 'string',
      default: 'USD',
    },
    tools: {
      type: 'string',
      default: '',
    },
    supplies: {
      type: 'string',
      default: '',
    },
    steps: {
      type: 'array',
      default: [{ title: '', text: '' }],
    },
    className: {
      type: 'string',
      default: '',
    },
  },
  edit: Edit,
  save: () => null,
});
