// Touch-friendly input fields: DateField, PhoneField, StateField

function formatDate(iso) {
  if (!iso) return '';
  const d = new Date(iso + 'T00:00:00');
  if (isNaN(d)) return iso;
  return d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });
}

function toISO(d) {
  const y = d.getFullYear(), m = String(d.getMonth()+1).padStart(2,'0'), day = String(d.getDate()).padStart(2,'0');
  return `${y}-${m}-${day}`;
}

function DateField({ id, value, onChange, required, maxToday = true }) {
  const [open, setOpen] = React.useState(false);
  return (
    <>
      <button id={id} type="button" onClick={() => setOpen(true)}
        className={`w-full h-11 px-3 rounded-lg border bg-white flex items-center justify-between text-left
          ${value ? 'border-neutral-300 text-neutral-900' : 'border-neutral-300 text-neutral-400'}
          hover:border-neutral-400 focus:border-[var(--s3-orange)] focus:ring-4 focus:ring-orange-200 focus:outline-none transition-colors`}>
        <span className="text-[15px]">{value ? formatDate(value) : 'Select date'}</span>
        <IconCalendar size={16} className="text-neutral-400"/>
      </button>
      <DatePickerSheet open={open} initial={value} maxToday={maxToday}
        onClose={() => setOpen(false)}
        onConfirm={(v) => { onChange(v); setOpen(false); }}/>
    </>
  );
}

function DatePickerSheet({ open, initial, maxToday, onClose, onConfirm }) {
  const today = new Date();
  const todayISO = toISO(today);
  const [month, setMonth] = React.useState(() => {
    const d = initial ? new Date(initial + 'T00:00:00') : today;
    return new Date(d.getFullYear(), d.getMonth(), 1);
  });
  const [picked, setPicked] = React.useState(initial || '');

  React.useEffect(() => {
    if (open) {
      setPicked(initial || '');
      const d = initial ? new Date(initial + 'T00:00:00') : today;
      setMonth(new Date(d.getFullYear(), d.getMonth(), 1));
    }
  }, [open, initial]);

  if (!open) return null;

  const quick = [
    { label: 'Today', iso: todayISO },
    { label: 'Yesterday', iso: toISO(new Date(today.getFullYear(), today.getMonth(), today.getDate()-1)) },
    { label: '2 days ago', iso: toISO(new Date(today.getFullYear(), today.getMonth(), today.getDate()-2)) },
    { label: 'Last week', iso: toISO(new Date(today.getFullYear(), today.getMonth(), today.getDate()-7)) },
  ];

  const y = month.getFullYear(), m = month.getMonth();
  const firstDay = new Date(y, m, 1).getDay();
  const daysInMonth = new Date(y, m+1, 0).getDate();
  const offset = (firstDay + 6) % 7;
  const weeks = [];
  let cells = [];
  for (let i = 0; i < offset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7) cells.push(null);
  for (let i = 0; i < cells.length; i += 7) weeks.push(cells.slice(i, i+7));

  const monthLabel = month.toLocaleString('en-GB', { month: 'long', year: 'numeric' });
  const prevMonth = () => setMonth(new Date(y, m-1, 1));
  const nextMonth = () => setMonth(new Date(y, m+1, 1));
  const nextDisabled = maxToday && (y > today.getFullYear() || (y === today.getFullYear() && m >= today.getMonth()));

  const isFuture = (d) => {
    if (!maxToday) return false;
    return new Date(y, m, d) > today;
  };

  return (
    <div className="fixed inset-0 z-40" onClick={onClose}>
      <div className="absolute inset-0 bg-black/50" style={{animation:'fadeIn 180ms ease'}}/>
      <div onClick={e => e.stopPropagation()}
        className="absolute left-0 right-0 bottom-0 bg-white rounded-t-2xl shadow-2xl"
        style={{animation:'slideUp 260ms cubic-bezier(0.22,1,0.36,1)'}}>
        <div className="flex items-center justify-center pt-2 pb-1">
          <div className="w-10 h-1 rounded-full bg-neutral-300"/>
        </div>
        <div className="flex items-center justify-between px-5 py-3 border-b border-neutral-100">
          <button onClick={onClose} className="text-[14px] text-neutral-500">Cancel</button>
          <div className="font-semibold text-[15px]">Purchase date</div>
          <button onClick={() => picked && onConfirm(picked)}
            disabled={!picked}
            className="text-[14px] font-semibold text-[var(--s3-orange)] disabled:opacity-40">Done</button>
        </div>
        <div className="flex gap-2 px-4 pt-3 overflow-x-auto scrollbar-none">
          {quick.map(q => (
            <button key={q.label} onClick={() => setPicked(q.iso)}
              className={`shrink-0 h-8 px-3 rounded-full text-[12.5px] font-medium transition-colors
                ${picked === q.iso ? 'bg-[var(--s3-orange)] text-white' : 'bg-neutral-100 text-neutral-700 hover:bg-neutral-200'}`}>
              {q.label}
            </button>
          ))}
        </div>
        <div className="px-4 pt-4 pb-2">
          <div className="flex items-center justify-between mb-2">
            <button onClick={prevMonth} className="w-9 h-9 rounded-lg hover:bg-neutral-100 grid place-items-center">
              <IconChevronLeft size={18}/>
            </button>
            <div className="text-[14px] font-semibold">{monthLabel}</div>
            <button onClick={nextMonth} disabled={nextDisabled}
              className="w-9 h-9 rounded-lg hover:bg-neutral-100 grid place-items-center disabled:opacity-30">
              <IconChevronRight size={18}/>
            </button>
          </div>
          <div className="grid grid-cols-7 gap-1 text-center mb-1">
            {['M','T','W','T','F','S','S'].map((w,i) => (
              <div key={i} className="text-[10.5px] font-semibold text-neutral-400 uppercase tracking-wider">{w}</div>
            ))}
          </div>
          <div className="grid grid-cols-7 gap-1">
            {weeks.flat().map((d, i) => {
              if (!d) return <div key={i}/>;
              const iso = toISO(new Date(y, m, d));
              const isPicked = iso === picked;
              const isToday = iso === todayISO;
              const future = isFuture(d);
              return (
                <button key={i} onClick={() => !future && setPicked(iso)}
                  disabled={future}
                  className={`h-10 rounded-lg text-[14px] font-medium transition-all active:scale-95
                    ${isPicked ? 'bg-[var(--s3-orange)] text-white shadow-sm'
                      : isToday ? 'bg-orange-50 text-[var(--s3-orange)] ring-1 ring-orange-200'
                      : future ? 'text-neutral-300' : 'text-neutral-800 hover:bg-neutral-100'}`}>
                  {d}
                </button>
              );
            })}
          </div>
        </div>
        <div className="p-4 pb-8 border-t border-neutral-100 mt-2 bg-neutral-50">
          <div className="text-[11.5px] text-neutral-500 uppercase tracking-wider mb-1">Selected</div>
          <div className="text-[16px] font-semibold text-neutral-900">
            {picked ? formatDate(picked) : 'No date selected'}
          </div>
        </div>
      </div>
    </div>
  );
}

function formatMyPhone(raw) {
  const d = raw.replace(/\D/g, '').slice(0, 10);
  if (d.length <= 2) return d;
  if (d.length <= 5) return `${d.slice(0,2)}-${d.slice(2)}`;
  return `${d.slice(0,2)}-${d.slice(2,5)} ${d.slice(5)}`;
}

function PhoneField({ id, value, onChange, placeholder = '12-345 6789' }) {
  return (
    <div className="flex h-11 rounded-lg border border-neutral-300 bg-white overflow-hidden
      focus-within:border-[var(--s3-orange)] focus-within:ring-4 focus-within:ring-orange-200 transition-colors">
      <div className="shrink-0 flex items-center gap-1.5 px-3 bg-neutral-50 border-r border-neutral-200 text-[14.5px] font-medium text-neutral-700">
        <span>🇲🇾</span>
        <span>+60</span>
      </div>
      <input id={id} type="tel" inputMode="tel" autoComplete="tel-national"
        value={value} onChange={e => onChange(formatMyPhone(e.target.value))}
        placeholder={placeholder}
        className="flex-1 px-3 text-[15px] text-neutral-900 placeholder:text-neutral-400 focus:outline-none bg-white"/>
    </div>
  );
}

function StateField({ id, value, onChange, states }) {
  const [open, setOpen] = React.useState(false);
  return (
    <>
      <button id={id} type="button" onClick={() => setOpen(true)}
        className={`w-full h-11 px-3 rounded-lg border bg-white flex items-center justify-between text-left
          ${value ? 'text-neutral-900' : 'text-neutral-400'}
          border-neutral-300 hover:border-neutral-400 focus:border-[var(--s3-orange)] focus:ring-4 focus:ring-orange-200 focus:outline-none transition-colors`}>
        <span className="text-[15px]">{value || 'Select state…'}</span>
        <IconChevronDown size={16} className="text-neutral-400"/>
      </button>
      {open && (
        <div className="fixed inset-0 z-40" onClick={() => setOpen(false)}>
          <div className="absolute inset-0 bg-black/50" style={{animation:'fadeIn 180ms ease'}}/>
          <div onClick={e => e.stopPropagation()}
            className="absolute left-0 right-0 bottom-0 bg-white rounded-t-2xl shadow-2xl max-h-[80%] flex flex-col"
            style={{animation:'slideUp 260ms cubic-bezier(0.22,1,0.36,1)'}}>
            <div className="flex items-center justify-center pt-2 pb-1 shrink-0">
              <div className="w-10 h-1 rounded-full bg-neutral-300"/>
            </div>
            <div className="flex items-center justify-between px-5 py-3 border-b border-neutral-100 shrink-0">
              <button onClick={() => setOpen(false)} className="text-[14px] text-neutral-500">Cancel</button>
              <div className="font-semibold text-[15px]">Select state</div>
              <span className="w-12"/>
            </div>
            <div className="flex-1 overflow-auto">
              {states.map(s => (
                <button key={s} onClick={() => { onChange(s); setOpen(false); }}
                  className={`w-full flex items-center justify-between px-5 py-3.5 text-left text-[15px] border-b border-neutral-50 active:bg-neutral-100
                    ${value === s ? 'text-[var(--s3-orange)] font-semibold bg-orange-50/40' : 'text-neutral-900'}`}>
                  {s}
                  {value === s && <IconCheck size={16} sw={2.5}/>}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { DateField, PhoneField, StateField, formatMyPhone });
