// ChefForm — add/edit modal (formal layout)

function ChefForm({ initial, onCancel, onSave, existingIds }) {
  const blank = {
    id: "", name: "", phone: "", age: "",
    currentGov: "بغداد", acceptedGovs: [],
    specialty: "مشويات", expYears: "", expPlaces: "",
    lastPlace: "", salary: "",
    accomm: false, outside: false,
    portfolio: "",
    status: "جديد", rating: "يحتاج تجربة",
    notes: ""
  };
  const [f, setF] = React.useState(() => ({ ...blank, ...(initial||{}) }));
  const isEdit = !!initial;

  function up(k, v){ setF(prev => ({...prev, [k]: v})) }
  function toggleGov(g){
    setF(prev => {
      const has = prev.acceptedGovs.includes(g);
      return {...prev, acceptedGovs: has ? prev.acceptedGovs.filter(x=>x!==g) : [...prev.acceptedGovs, g]};
    });
  }
  function selectAllGovs(){ setF(prev => ({...prev, acceptedGovs: [...GOVERNORATES]})) }
  function clearGovs(){ setF(prev => ({...prev, acceptedGovs: []})) }

  function submit(e){
    e?.preventDefault?.();
    if(!f.name.trim()){ alert("يرجى إدخال الاسم الثلاثي"); return }
    if(!f.phone.trim()){ alert("يرجى إدخال رقم الهاتف"); return }
    const data = {
      ...f,
      age: f.age ? Number(f.age) : "",
      expYears: f.expYears ? Number(f.expYears) : "",
      salary: f.salary ? Number(String(f.salary).replace(/[^\d]/g,"")) : "",
      acceptedGovs: f.acceptedGovs.length ? f.acceptedGovs : [f.currentGov],
      id: f.id || window.nextId(existingIds.map(id => ({id}))),
      createdAt: f.createdAt || Date.now()
    };
    onSave(data);
  }

  const previewId = f.id || window.nextId(existingIds.map(id => ({id})));

  return (
    <div className="modal-overlay" onClick={onCancel}>
      <form className="modal" onClick={e=>e.stopPropagation()} onSubmit={submit}>
        <div className="modal-head">
          <div>
            <div className="modal-title">{isEdit ? "تعديل بيانات الشيف" : "إضافة شيف جديد"}</div>
            <div className="modal-title-sub">{previewId}</div>
          </div>
          <button type="button" className="modal-close" onClick={onCancel} aria-label="إغلاق">
            <Icon name="x" size={18}/>
          </button>
        </div>

        <div className="modal-body">
          {/* Section 1: Personal */}
          <div className="form-section">
            <div className="form-section-title">المعلومات الشخصية</div>
            <div className="form-grid">
              <div className="field full">
                <label className="label">الاسم الثلاثي <span className="req">*</span></label>
                <input className="input" value={f.name} onChange={e=>up("name",e.target.value)} placeholder="مثال: أحمد كريم حسن" autoFocus/>
              </div>
              <div className="field">
                <label className="label">رقم الهاتف / واتساب <span className="req">*</span></label>
                <input className="input" value={f.phone} onChange={e=>up("phone",e.target.value)} placeholder="07XX XXX XXXX" type="tel" dir="ltr" style={{textAlign:"right"}}/>
              </div>
              <div className="field">
                <label className="label">العمر</label>
                <input className="input" value={f.age} onChange={e=>up("age",e.target.value.replace(/\D/g,""))} placeholder="مثال: 32" inputMode="numeric"/>
              </div>
            </div>
          </div>

          {/* Section 2: Location */}
          <div className="form-section">
            <div className="form-section-title">المحافظة والتنقل</div>
            <div className="form-grid">
              <div className="field">
                <label className="label">المحافظة الحالية</label>
                <select className="select" value={f.currentGov} onChange={e=>up("currentGov",e.target.value)}>
                  {GOVERNORATES.map(g => <option key={g} value={g}>{g}</option>)}
                </select>
              </div>
              <div className="field">
                <label className="label">يقبل العمل خارج محافظته؟</label>
                <div className="toggle-row">
                  <button type="button" className={"toggle" + (f.outside ? " on" : "")} onClick={()=>up("outside",true)}>
                    <Icon name="check" size={13}/> نعم
                  </button>
                  <button type="button" className={"toggle no" + (!f.outside ? " on" : "")} onClick={()=>up("outside",false)}>
                    لا
                  </button>
                </div>
              </div>
              <div className="field full">
                <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
                  <label className="label">المحافظات المقبولة للعمل ({f.acceptedGovs.length})</label>
                  <div style={{display:"flex",gap:6}}>
                    <button type="button" className="btn btn-sm btn-ghost" onClick={selectAllGovs} style={{height:24, fontSize:11}}>تحديد الكل</button>
                    <button type="button" className="btn btn-sm btn-ghost" onClick={clearGovs} style={{height:24, fontSize:11}}>مسح</button>
                  </div>
                </div>
                <div className="gov-grid">
                  {GOVERNORATES.map(g => (
                    <button type="button" key={g}
                            className={"gov-pill" + (f.acceptedGovs.includes(g) ? " on" : "")}
                            onClick={()=>toggleGov(g)}>
                      {f.acceptedGovs.includes(g) && <Icon name="check" size={10} stroke={2.5}/>} {g}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* Section 3: Professional */}
          <div className="form-section">
            <div className="form-section-title">المعلومات المهنية</div>
            <div className="form-grid">
              <div className="field">
                <label className="label">الاختصاص</label>
                <select className="select" value={f.specialty} onChange={e=>up("specialty",e.target.value)}>
                  {SPECIALTIES.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div className="field">
                <label className="label">سنوات الخبرة</label>
                <input className="input" value={f.expYears} onChange={e=>up("expYears",e.target.value.replace(/\D/g,""))} placeholder="مثال: 5" inputMode="numeric"/>
              </div>
              <div className="field full">
                <label className="label">أماكن العمل السابقة</label>
                <input className="input" value={f.expPlaces} onChange={e=>up("expPlaces",e.target.value)} placeholder="مطعم السلطان، مطعم نارنج، فندق...."/>
              </div>
              <div className="field full">
                <label className="label">آخر مكان عمل</label>
                <input className="input" value={f.lastPlace} onChange={e=>up("lastPlace",e.target.value)} placeholder="اسم المطعم + المنطقة"/>
              </div>
              <div className="field full">
                <label className="label">رابط فيديو أو صور الشغل (اختياري)</label>
                <input className="input" value={f.portfolio} onChange={e=>up("portfolio",e.target.value)} placeholder="https://..." type="url" dir="ltr" style={{textAlign:"right"}}/>
              </div>
            </div>
          </div>

          {/* Section 4: Offer */}
          <div className="form-section">
            <div className="form-section-title">العرض والتقييم</div>
            <div className="form-grid">
              <div className="field">
                <label className="label">الراتب المطلوب (د.ع)</label>
                <input className="input tnum" value={f.salary} onChange={e=>up("salary",e.target.value.replace(/[^\d]/g,""))} placeholder="مثال: 1000000" inputMode="numeric" dir="ltr" style={{textAlign:"right"}}/>
              </div>
              <div className="field">
                <label className="label">يقبل سكن؟</label>
                <div className="toggle-row">
                  <button type="button" className={"toggle" + (f.accomm ? " on" : "")} onClick={()=>up("accomm",true)}>
                    <Icon name="check" size={13}/> نعم
                  </button>
                  <button type="button" className={"toggle no" + (!f.accomm ? " on" : "")} onClick={()=>up("accomm",false)}>
                    لا
                  </button>
                </div>
              </div>
              <div className="field">
                <label className="label">الحالة</label>
                <select className="select" value={f.status} onChange={e=>up("status",e.target.value)}>
                  {STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div className="field">
                <label className="label">التقييم السريع</label>
                <select className="select" value={f.rating} onChange={e=>up("rating",e.target.value)}>
                  {RATINGS.map(r => <option key={r} value={r}>{r}</option>)}
                </select>
              </div>
              <div className="field full">
                <label className="label">الملاحظات</label>
                <textarea className="textarea" value={f.notes} onChange={e=>up("notes",e.target.value)}
                          placeholder="مثال: محترم، سريع، شغله نظيف، قوي بالمشاوي، عنده خبرة فعلية..."/>
              </div>
            </div>
          </div>
        </div>

        <div className="modal-foot">
          <button type="button" className="btn" onClick={onCancel}>إلغاء</button>
          <button type="submit" className="btn btn-primary">
            <Icon name="check" size={14}/> {isEdit ? "حفظ التغييرات" : "إضافة السجل"}
          </button>
        </div>
      </form>
    </div>
  );
}

window.ChefForm = ChefForm;
