'use client';

import { useEffect, useRef } from 'react';

function isApplePlatform() {
  if (typeof navigator === 'undefined') return false;
  return /Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent || '');
}

/**
 * Cmd+K-style search input with a focus shortcut. The query is owned by the
 * parent shell — this component is a controlled input.
 *
 * @param {{ value: string, onChange: (value: string) => void }} props
 */
export default function MarketplaceSearch({ value, onChange }) {
  const inputRef = useRef(null);

  useEffect(() => {
    function onKeyDown(event) {
      const meta = event.metaKey || event.ctrlKey;
      if (meta && event.key.toLowerCase() === 'k') {
        event.preventDefault();
        inputRef.current?.focus();
        inputRef.current?.select();
      } else if (event.key === 'Escape' && document.activeElement === inputRef.current) {
        onChange('');
        inputRef.current?.blur();
      }
    }
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [onChange]);

  const modifierLabel = isApplePlatform() ? '⌘' : 'Ctrl';

  return (
    <div className="mkt-search" role="search">
      <svg
        className="mkt-search-icon"
        width="18"
        height="18"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.7"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <circle cx="11" cy="11" r="7" />
        <path d="M21 21l-4.3-4.3" />
      </svg>
      <input
        ref={inputRef}
        type="search"
        className="mkt-search-input"
        placeholder="Search tools, skills, bundles, authors…"
        value={value}
        onChange={e => onChange(e.target.value)}
        aria-label="Search marketplace"
      />
      <span className="mkt-search-kbd" aria-hidden="true">
        <kbd>{modifierLabel}</kbd>
        <kbd>K</kbd>
      </span>
    </div>
  );
}
