/* global React, ReactDOM, LeadFormUtils */
const { useState, useRef, useEffect, useMemo } = React;
const U = window.LeadFormUtils;

/* ---------------- Shared little bits ---------------- */
function Icon({ d, size = 20, stroke = 'currentColor', className = '' }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke={stroke}
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
    >
      {d}
    </svg>
  );
}

const ICONS = {
  drop: <><path d="M12 3s-6 7.5-6 12a6 6 0 0 0 12 0c0-4.5-6-12-6-12Z" /></>,
  bolt: <><path d="M13 2 4 14h7l-1 8 9-12h-7l1-8Z" /></>,
  shield: <><path d="M12 3 4 6v6c0 5 3.5 8.5 8 9 4.5-.5 8-4 8-9V6l-8-3Z" /><path d="m9 12 2 2 4-4" /></>,
  clock: <><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></>,
  phone: <><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92Z" /></>,
  check: <><path d="m5 12 5 5 9-11" /></>,
  user: <><circle cx="12" cy="8" r="4" /><path d="M4 20c0-4 4-6 8-6s8 2 8 6" /></>,
  camera: <><path d="M3 7h4l2-3h6l2 3h4v13H3z" /><circle cx="12" cy="13" r="4" /></>,
  x: <><path d="M6 6l12 12M18 6 6 18" /></>,
  star: <><path d="m12 3 2.9 5.9 6.5.9-4.7 4.6 1.1 6.5L12 17.8 6.2 21l1.1-6.5L2.6 9.8l6.5-.9L12 3Z" /></>,
  arrow: <><path d="M5 12h14M13 5l7 7-7 7" /></>,
  alert: <><circle cx="12" cy="12" r="9" /><path d="M12 8v5M12 16h.01" /></>,
};

/* ---------------- Phone input ---------------- */
function PhoneInput({ value, onChange, error, dark }) {
  const ref = useRef(null);
  return (
    <input
      ref={ref}
      type="tel"
      inputMode="tel"
      autoComplete="tel"
      placeholder="+7 (___) ___-__-__"
      value={value}
      onChange={(e) => onChange(U.formatPhoneKZ(e.target.value))}
      onFocus={(e) => { if (!value) onChange('+7 ('); }}
      onKeyDown={(e) => {
        if (e.key === 'Backspace') {
          const d = U.digitsOnly(value);
          if (d.length <= 1) { e.preventDefault(); onChange(''); }
        }
      }}
      className={`w-full px-4 py-3.5 rounded-xl border-2 outline-none transition text-[15px] tabular-nums ${
        dark
          ? `bg-white/5 text-white placeholder-white/30 ${error ? 'border-red-400/70' : 'border-white/10 focus:border-[#fdbe11]'}`
          : `bg-white text-slate-900 placeholder-slate-400 ${error ? 'border-red-400' : 'border-slate-200 focus:border-[#11274e]'}`
      }`}
    />
  );
}

/* ---------------- Photo dropzone ---------------- */
function PhotoUpload({ files, setFiles, dark }) {
  const inputRef = useRef(null);
  const [dragOver, setDragOver] = useState(false);
  const [error, setError] = useState('');

  const handle = (incoming) => {
    const merged = [...files, ...incoming];
    const { accepted, errors } = U.validateFiles(merged);
    setFiles(accepted);
    setError(errors[0] || '');
  };

  return (
    <div>
      <div
        onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={(e) => {
          e.preventDefault(); setDragOver(false);
          handle(Array.from(e.dataTransfer.files || []));
        }}
        onClick={() => inputRef.current?.click()}
        className={`cursor-pointer rounded-xl border-2 border-dashed px-4 py-4 flex items-center gap-3 transition ${
          dragOver
            ? (dark ? 'border-[#fdbe11] bg-[#fdbe11]/10' : 'border-[#fdbe11] bg-yellow-50')
            : (dark ? 'border-white/15 hover:border-white/30 bg-white/[0.02]' : 'border-slate-200 hover:border-slate-300 bg-slate-50')
        }`}
      >
        <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${dark ? 'bg-white/10 text-white' : 'bg-white text-slate-700 border border-slate-200'}`}>
          <Icon d={ICONS.camera} size={20} />
        </div>
        <div className="flex-1 min-w-0">
          <div className={`text-[13.5px] font-semibold ${dark ? 'text-white' : 'text-slate-900'}`}>
            Прикрепите фото — необязательно
          </div>
          <div className={`text-[12px] ${dark ? 'text-white/50' : 'text-slate-500'}`}>
            До 5 фото · JPG, PNG, WEBP · до 8 МБ
          </div>
        </div>
        <span className={`text-[12px] font-semibold uppercase tracking-wider ${dark ? 'text-[#fdbe11]' : 'text-[#11274e]'}`}>Выбрать</span>
      </div>
      <input
        ref={inputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp,image/heic,image/heif"
        multiple
        hidden
        onChange={(e) => handle(Array.from(e.target.files || []))}
      />
      {error && <div className="mt-2 text-[12.5px] text-red-500">{error}</div>}
      {files.length > 0 && (
        <div className="mt-3 flex flex-wrap gap-2">
          {files.map((f, i) => (
            <div
              key={i}
              className={`flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-[12px] ${
                dark ? 'bg-white/10 text-white/90' : 'bg-slate-100 text-slate-700'
              }`}
            >
              <Icon d={ICONS.camera} size={13} />
              <span className="max-w-[160px] truncate">{f.name}</span>
              <button
                type="button"
                onClick={(e) => { e.stopPropagation(); setFiles(files.filter((_, j) => j !== i)); }}
                className={`p-0.5 rounded ${dark ? 'hover:bg-white/10' : 'hover:bg-slate-200'}`}
                aria-label="Удалить"
              >
                <Icon d={ICONS.x} size={12} />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------------- Lead form (configurable look) ----------------
 * Props:
 *   dark — boolean, switch palette
 *   accent — 'yellow' | 'blue' (button color)
 *   title, subtitle — heading content
 */
function LeadForm({ dark = false, accent = 'yellow', title, subtitle, compact = false, defaultService = '' }) {
  const [values, setValues] = useState({
    name: '',
    phone: '',
    service: defaultService,
    description: '',
    consent: true,
    city: 'Астана',
  });
  const [files, setFiles] = useState([]);
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(null); // null | {ok, id}
  const [honeypot, setHoneypot] = useState('');
  const formStartRef = useRef(Date.now());

  const set = (k) => (v) => setValues((s) => ({ ...s, [k]: v }));
  const onBlur = (k) => () => setTouched((s) => ({ ...s, [k]: true }));

  const liveErrors = useMemo(() => U.validate(values), [values]);
  const show = (k) => (touched[k] || Object.keys(errors).length > 0) && liveErrors[k];

  const handleSubmit = async (e) => {
    e.preventDefault();
    // Bot checks: honeypot filled or submitted too fast (<3s)
    if (honeypot) return;
    if (Date.now() - formStartRef.current < 3000) return;
    const errs = U.validate(values);
    setErrors(errs);
    setTouched({ name: true, phone: true, service: true, description: true, consent: true });
    if (Object.keys(errs).length > 0) return;
    setSubmitting(true);
    try {
      const res = await U.submitLead(values, files, honeypot);
      setSubmitted(res || { ok: true });
    } catch (_) {
      setSubmitted({ ok: false });
    } finally {
      setSubmitting(false);
    }
  };

  const cardBg = dark ? 'bg-[#0c1a36] border border-white/10' : 'bg-white border border-slate-200 shadow-[0_30px_60px_-20px_rgba(17,39,78,0.25)]';
  const labelCls = `block text-[12.5px] font-semibold uppercase tracking-[0.06em] mb-1.5 ${dark ? 'text-white/60' : 'text-slate-500'}`;
  const inputCls = (err) =>
    `w-full px-4 py-3.5 rounded-xl border-2 outline-none transition text-[15px] ${
      dark
        ? `bg-white/5 text-white placeholder-white/30 ${err ? 'border-red-400/70' : 'border-white/10 focus:border-[#fdbe11]'}`
        : `bg-white text-slate-900 placeholder-slate-400 ${err ? 'border-red-400' : 'border-slate-200 focus:border-[#11274e]'}`
    }`;
  const btnAccent = accent === 'yellow'
    ? 'bg-[#fdbe11] hover:bg-[#e3a800] text-[#11274e]'
    : 'bg-[#11274e] hover:bg-[#1a3669] text-white';

  if (submitted?.ok) {
    return (
      <div className={`rounded-2xl p-7 ${cardBg}`}>
        <div className="w-14 h-14 rounded-full bg-emerald-500/15 text-emerald-500 flex items-center justify-center mb-4">
          <Icon d={ICONS.check} size={28} />
        </div>
        <h3 className={`text-[22px] font-bold mb-2 ${dark ? 'text-white' : 'text-slate-900'}`}>
          Заявка принята
        </h3>
        <p className={`text-[14.5px] leading-relaxed ${dark ? 'text-white/70' : 'text-slate-600'}`}>
          Менеджер позвонит на <span className="font-semibold">{values.phone}</span> в течение 15 минут.
          {submitted.mocked && <span className={`block mt-2 text-[12px] ${dark ? 'text-white/40' : 'text-slate-400'}`}>* demo — реальная отправка пойдёт на /api/leads</span>}
        </p>
        <button
          type="button"
          onClick={() => { setSubmitted(null); setValues({ name: '', phone: '', service: '', description: '', consent: true, city: 'Астана' }); setFiles([]); setTouched({}); setErrors({}); }}
          className={`mt-5 text-[13px] font-semibold ${dark ? 'text-[#fdbe11] hover:text-yellow-300' : 'text-[#11274e] hover:text-[#1a3669]'}`}
        >
          Отправить ещё одну заявку →
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} noValidate className={`rounded-2xl ${cardBg} ${compact ? 'p-5' : 'p-6 md:p-7'}`}>
      {title && (
        <div className="mb-5">
          <h3 className={`text-[20px] md:text-[22px] font-bold leading-tight ${dark ? 'text-white' : 'text-slate-900'}`}>{title}</h3>
          {subtitle && <p className={`mt-1.5 text-[13.5px] ${dark ? 'text-white/60' : 'text-slate-500'}`}>{subtitle}</p>}
        </div>
      )}

      {/* Service toggle removed */}

      <div className="mb-4">
        <label className={labelCls}>Телефон</label>
        <PhoneInput value={values.phone} onChange={set('phone')} error={show('phone')} dark={dark} />
        {show('phone') && <div className="mt-1.5 text-[12.5px] text-red-500">{liveErrors.phone}</div>}
      </div>

      <div className="mb-4">
        <label className={labelCls}>Что случилось — кратко</label>
        <textarea
          rows={3}
          placeholder="Течёт смеситель на кухне, нужно заменить. Дом 2018 года, разводка медь."
          value={values.description}
          onChange={(e) => set('description')(e.target.value)}
          onBlur={onBlur('description')}
          maxLength={600}
          className={`${inputCls(show('description'))} resize-none`}
        />
        <div className="flex items-center justify-between mt-1.5">
          {show('description')
            ? <div className="text-[12.5px] text-red-500">{liveErrors.description}</div>
            : <div className={`text-[12px] ${dark ? 'text-white/40' : 'text-slate-400'}`}>Чем подробнее — тем точнее оценка</div>}
          <div className={`text-[12px] tabular-nums ${dark ? 'text-white/40' : 'text-slate-400'}`}>{values.description.length}/600</div>
        </div>
      </div>



      {/* Honeypot — hidden from real users, bots fill it automatically */}
      <input
        type="text"
        name="website"
        value={honeypot}
        onChange={(e) => setHoneypot(e.target.value)}
        tabIndex={-1}
        autoComplete="off"
        aria-hidden="true"
        style={{ position: 'absolute', left: '-9999px', width: '1px', height: '1px', opacity: 0 }}
      />

      <button
        type="submit"
        disabled={submitting}
        className={`group w-full px-5 py-4 rounded-xl font-bold text-[15.5px] transition flex items-center justify-center gap-2 ${btnAccent} ${submitting ? 'opacity-70 cursor-wait' : 'hover:translate-y-[-1px] hover:shadow-lg'}`}
      >
        {submitting ? (
          <>
            <span className="w-4 h-4 border-2 border-current border-r-transparent rounded-full animate-spin" />
            Отправляем…
          </>
        ) : (
          <>
            Получить расчёт за 15 минут
            <Icon d={ICONS.arrow} size={18} className="transition group-hover:translate-x-1" />
          </>
        )}
      </button>

      <p className={`mt-3 text-center text-[11.5px] leading-relaxed ${dark ? 'text-white/40' : 'text-slate-400'}`}>
        Нажимая кнопку, вы соглашаетесь с{' '}
        <a href="#privacy" onClick={(e) => e.preventDefault()} className={`underline underline-offset-2 ${dark ? 'text-white/60' : 'text-slate-500'}`}>
          обработкой персональных данных
        </a>
      </p>
    </form>
  );
}

window.LeadForm = LeadForm;
window.LF_Icon = Icon;
window.LF_ICONS = ICONS;
