// ═══════════════════════════════════════════════════════════════
//  Meeting Editor — Add/Edit meetings for approved activities
//  Supports recurring (e.g. every Tuesday x4)
// ═══════════════════════════════════════════════════════════════

const { useState: uSME, useEffect: uEME } = React;

window.MeetingEditorModal = function MeetingEditorModal({ open, onClose, activity }) {
  const { state, addMeeting, updateMeeting, deleteMeeting } = window.useApp();
  const toast = window.useToast();
  const [mode, setMode] = uSME('single'); // 'single' or 'recurring'
  const [data, setData] = uSME({
    date: new Date().toISOString().slice(0, 10),
    startTime: '14:00',
    endTime: '16:00',
    location: '',
    topic: '',
    // Recurring
    dayOfWeek: 2, // Sunday=0
    count: 4,
    startFrom: new Date().toISOString().slice(0, 10)
  });

  uEME(() => {
    if (open && activity) {
      const auth = state.authorities.find(a => a.id === activity.authorityId);
      setData(d => ({ ...d, location: auth?.name || '', topic: activity.activityName || '' }));
    }
  }, [open, activity]);

  if (!open || !activity) return null;

  const activityMeetings = (state.meetings || []).filter(m => m.activityId === activity.id).sort((a, b) => a.date.localeCompare(b.date));

  const days = ['ראשון', 'שני', 'שלישי', 'רביעי', 'חמישי', 'שישי', 'שבת'];

  const addSingle = () => {
    if (!data.date || !data.startTime) { toast.push({ type: 'error', message: 'תאריך ושעה נדרשים' }); return; }
    addMeeting({
      activityId: activity.id,
      authorityId: activity.authorityId,
      date: data.date,
      startTime: data.startTime,
      endTime: data.endTime,
      location: data.location,
      topic: data.topic
    });
    toast.push({ type: 'success', message: 'מפגש נוסף ליומן' });
  };

  const addRecurring = () => {
    if (!data.startFrom || !data.startTime || !data.count) { toast.push({ type: 'error', message: 'נתונים חסרים' }); return; }
    // Find the next occurrence of the chosen weekday on or after startFrom
    const start = new Date(data.startFrom);
    const startDow = start.getDay();
    let offset = (data.dayOfWeek - startDow + 7) % 7;
    const count = Math.min(Number(data.count), 52);
    const auth = state.authorities.find(a => a.id === activity.authorityId);

    for (let i = 0; i < count; i++) {
      const d = new Date(start);
      d.setDate(d.getDate() + offset + i * 7);
      addMeeting({
        activityId: activity.id,
        authorityId: activity.authorityId,
        date: d.toISOString().slice(0, 10),
        startTime: data.startTime,
        endTime: data.endTime,
        location: data.location,
        topic: `${data.topic} · מפגש ${i + 1}/${count}`,
        lat: auth?.lat, lng: auth?.lng
      });
    }
    toast.push({ type: 'success', title: 'נוספו מפגשים', message: `${count} מפגשים כל יום ${days[data.dayOfWeek]}` });
    setData(d => ({ ...d, count: 4 }));
  };

  return (
    <window.Modal
      open={open}
      onClose={onClose}
      title={
        <div className="flex items-center gap-2">
          <div className="w-9 h-9 rounded-lg bg-brand-100 text-brand-700 flex items-center justify-center">
            <window.Icon.Calendar size={18}/>
          </div>
          <div>
            <div>עדכון מפגשים</div>
            <div className="text-xs font-normal text-slate-500 truncate max-w-md">{activity.activityName}</div>
          </div>
        </div>
      }
      size="lg"
      footer={<window.Button variant="primary" onClick={onClose}>סגור</window.Button>}
    >
      {/* Existing meetings */}
      {activityMeetings.length > 0 && (
        <div className="mb-5">
          <div className="text-xs font-semibold text-slate-500 mb-2">מפגשים קיימים · {activityMeetings.length}</div>
          <div className="space-y-1.5 max-h-44 overflow-y-auto">
            {activityMeetings.map(m => (
              <div key={m.id} className="flex items-center gap-3 p-2.5 rounded-lg border border-slate-200 bg-slate-50 text-sm">
                <div className="text-center shrink-0 w-16">
                  <div className="text-[10px] text-slate-500">{window.hebrewDayName?.(new Date(m.date))?.replace('יום ', '') || ''}</div>
                  <div className="font-display font-bold">{new Date(m.date).getDate()}/{new Date(m.date).getMonth() + 1}</div>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="font-semibold text-xs truncate">{m.topic}</div>
                  <div className="text-[11px] text-slate-500">{m.startTime}–{m.endTime} · {m.location}</div>
                </div>
                <button onClick={() => {
                  if (confirm('למחוק מפגש זה?')) { deleteMeeting(m.id); toast.push({ message: 'נמחק' }); }
                }} className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg">
                  <window.Icon.Trash size={13}/>
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Mode switcher */}
      <div className="grid grid-cols-2 gap-2 mb-4">
        <button onClick={() => setMode('single')}
          className={`p-3 rounded-xl border-2 text-right transition-all ${mode === 'single' ? 'border-brand-500 bg-brand-50' : 'border-slate-200 bg-white'}`}>
          <div className="flex items-center gap-1.5 mb-1">
            <window.Icon.Calendar size={14} className="text-brand-600"/>
            <div className="font-display font-bold text-sm">מפגש בודד</div>
          </div>
          <div className="text-[11px] text-slate-500">הוספת מפגש אחד</div>
        </button>
        <button onClick={() => setMode('recurring')}
          className={`p-3 rounded-xl border-2 text-right transition-all ${mode === 'recurring' ? 'border-emerald-500 bg-emerald-50' : 'border-slate-200 bg-white'}`}>
          <div className="flex items-center gap-1.5 mb-1">
            <window.Icon.Activity size={14} className="text-emerald-600"/>
            <div className="font-display font-bold text-sm">מפגשים חוזרים</div>
          </div>
          <div className="text-[11px] text-slate-500">למשל כל יום שלישי × 4</div>
        </button>
      </div>

      {mode === 'single' ? (
        <div className="p-4 rounded-xl bg-slate-50 space-y-3">
          <div className="grid grid-cols-3 gap-3">
            <window.Field label="תאריך">
              <input type="date" value={data.date} onChange={e => setData(d => ({ ...d, date: e.target.value }))} className="input text-sm py-1.5"/>
            </window.Field>
            <window.Field label="שעת התחלה">
              <input type="time" value={data.startTime} onChange={e => setData(d => ({ ...d, startTime: e.target.value }))} className="input text-sm py-1.5"/>
            </window.Field>
            <window.Field label="שעת סיום">
              <input type="time" value={data.endTime} onChange={e => setData(d => ({ ...d, endTime: e.target.value }))} className="input text-sm py-1.5"/>
            </window.Field>
          </div>
          <window.Field label="נושא">
            <input value={data.topic} onChange={e => setData(d => ({ ...d, topic: e.target.value }))} className="input text-sm py-1.5" placeholder="למשל: מפגש ראשון"/>
          </window.Field>
          <window.Field label="מיקום">
            <input value={data.location} onChange={e => setData(d => ({ ...d, location: e.target.value }))} className="input text-sm py-1.5" placeholder="שם המקום, כתובת"/>
          </window.Field>
          <window.Button variant="primary" icon={<window.Icon.Plus size={14}/>} onClick={addSingle}>הוסף מפגש</window.Button>
        </div>
      ) : (
        <div className="p-4 rounded-xl bg-emerald-50 space-y-3">
          <div className="grid grid-cols-2 gap-3">
            <window.Field label="יום בשבוע">
              <select value={data.dayOfWeek} onChange={e => setData(d => ({ ...d, dayOfWeek: Number(e.target.value) }))} className="select text-sm py-1.5">
                {days.map((d, i) => <option key={i} value={i}>יום {d}</option>)}
              </select>
            </window.Field>
            <window.Field label="מספר מפגשים">
              <input type="number" min={1} max={52} value={data.count} onChange={e => setData(d => ({ ...d, count: Number(e.target.value) }))} className="input text-sm py-1.5 ltr-num"/>
            </window.Field>
            <window.Field label="מתחיל מתאריך">
              <input type="date" value={data.startFrom} onChange={e => setData(d => ({ ...d, startFrom: e.target.value }))} className="input text-sm py-1.5"/>
            </window.Field>
            <window.Field label="שעה">
              <div className="flex gap-1">
                <input type="time" value={data.startTime} onChange={e => setData(d => ({ ...d, startTime: e.target.value }))} className="input text-sm py-1.5"/>
                <input type="time" value={data.endTime} onChange={e => setData(d => ({ ...d, endTime: e.target.value }))} className="input text-sm py-1.5"/>
              </div>
            </window.Field>
          </div>
          <window.Field label="נושא">
            <input value={data.topic} onChange={e => setData(d => ({ ...d, topic: e.target.value }))} className="input text-sm py-1.5"/>
          </window.Field>
          <window.Field label="מיקום קבוע">
            <input value={data.location} onChange={e => setData(d => ({ ...d, location: e.target.value }))} className="input text-sm py-1.5"/>
          </window.Field>
          <div className="p-2.5 rounded-lg bg-white text-xs text-emerald-900 flex items-start gap-2">
            <window.Icon.Info size={12} className="text-emerald-600 shrink-0 mt-0.5"/>
            <div>ייווצרו {data.count} מפגשים · כל יום {days[data.dayOfWeek]} · החל מ-{data.startFrom}</div>
          </div>
          <window.Button variant="success" icon={<window.Icon.Plus size={14}/>} onClick={addRecurring}>צור {data.count} מפגשים</window.Button>
        </div>
      )}
    </window.Modal>
  );
};
