const { useState, useRef, useEffect, useMemo } = React;

/* ---------- Searchable country-code selector ---------- */
function CountrySelect({ value, onChange, idPrefix }) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const wrapRef = useRef(null);
  const searchRef = useRef(null);
  const sel = window.COUNTRIES.find((c) => c.c === value) || window.COUNTRIES[0];

  useEffect(() => {
    function onDoc(e) {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);

  useEffect(() => {
    if (open && searchRef.current) searchRef.current.focus();
    if (!open) setQ("");
  }, [open]);

  const list = useMemo(() => {
    const t = q.trim().toLowerCase();
    if (!t) return window.COUNTRIES;
    return window.COUNTRIES.filter(
      (c) =>
        c.n.toLowerCase().includes(t) ||
        c.d.includes(t.replace(/^\+/, "")) ||
        c.c.toLowerCase() === t
    );
  }, [q]);

  return (
    <div className="cc-wrap" ref={wrapRef}>
      <button
        type="button"
        className={"cc-trigger" + (open ? " is-open" : "")}
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={"Country code: " + sel.n + " +" + sel.d}
      >
        <img className="cc-flag" src={window.flagUrl(sel.c)} alt="" width="22" height="16" loading="lazy" />
        <span className="cc-dial">+{sel.d}</span>
        <svg className="cc-caret" viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
          <path d="M6 9l6 6 6-6" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </button>

      {open && (
        <div className="cc-panel" role="listbox">
          <div className="cc-search">
            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
              <circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" strokeWidth="2" />
              <path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
            </svg>
            <input
              ref={searchRef}
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Search country or code"
              aria-label="Search country"
            />
          </div>
          <div className="cc-list">
            {list.length === 0 && <div className="cc-empty">No matches</div>}
            {list.map((c) => (
              <button
                type="button"
                key={c.c + c.d}
                className={"cc-item" + (c.c === value ? " is-sel" : "")}
                onClick={() => {
                  onChange(c.c);
                  setOpen(false);
                }}
                role="option"
                aria-selected={c.c === value}
              >
                <img className="cc-flag" src={window.flagUrl(c.c)} alt="" width="24" height="18" loading="lazy" />
                <span className="cc-name">{c.n}</span>
                <span className="cc-itemdial">+{c.d}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- Phone input (country select + number) ---------- */
function PhoneField({ id, label, hint, iso, number, onIso, onNumber, error, optional, disabled }) {
  return (
    <div className="field">
      <label className="field-label" htmlFor={id}>
        {label}
        {optional && <span className="opt"> · optional</span>}
      </label>
      <div className={"phone-row" + (error ? " has-error" : "") + (disabled ? " is-disabled" : "")}>
        <CountrySelect value={iso} onChange={onIso} idPrefix={id} />
        <input
          id={id}
          type="tel"
          inputMode="tel"
          className="phone-input"
          placeholder="82 123 4567"
          value={number}
          onChange={(e) => onNumber(e.target.value.replace(/[^\d\s]/g, ""))}
          disabled={disabled}
          autoComplete="tel"
        />
      </div>
      {hint && !error && <div className="field-hint">{hint}</div>}
      {error && <div className="field-error">{error}</div>}
    </div>
  );
}

/* ---------- Text field ---------- */
function TextField({ id, label, type = "text", value, onChange, error, placeholder, hint, autoComplete, inputMode }) {
  return (
    <div className="field">
      <label className="field-label" htmlFor={id}>{label}</label>
      <input
        id={id}
        type={type}
        inputMode={inputMode}
        className={"text-input" + (error ? " has-error" : "")}
        value={value}
        placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
        autoComplete={autoComplete}
      />
      {hint && !error && <div className="field-hint">{hint}</div>}
      {error && <div className="field-error">{error}</div>}
    </div>
  );
}

/* ---------- Checkbox ---------- */
function Check({ id, checked, onChange, children, error }) {
  return (
    <label className={"check" + (error ? " has-error" : "")} htmlFor={id}>
      <input id={id} type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
      <span className="check-box" aria-hidden="true">
        <svg viewBox="0 0 24 24" width="14" height="14">
          <path d="M5 12.5l4.5 4.5L19 6.5" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </span>
      <span className="check-label">{children}</span>
    </label>
  );
}

Object.assign(window, { CountrySelect, PhoneField, TextField, Check });
