/* Category view + Enquiry modal */

const CategoryView = ({ catId, lang, onCategory, onEnquire, onNav }) => {
  const cat = window.BENO.categories.find(c => c.id === catId) || window.BENO.categories[0];
  const fleet = window.BENO.fleet[cat.id] || [];
  const process = window.BENO.process[cat.id] || window.BENO.process.cars;
  const T = window.BENO.copy[lang];

  return (
    <div className="view-enter">
      <section className="cat-hero">
        <div className="cat-hero-img" style={{ backgroundImage: `url(${cat.lifestyle || cat.img})` }}/>
        <div className="cat-hero-text">
          <div className="eyebrow eyebrow-light">
            <button onClick={() => onNav({ name: 'home' })} style={{ background: 'none', border: 0, color: 'inherit', padding: 0, cursor: 'pointer' }}>
              {lang === 'en' ? '← Back to home' : '→ العودة'}
            </button>
            <span style={{ margin: '0 12px', opacity: .4 }}>/</span>
            <span>{T.navRentals} · {cat.pill[lang]}</span>
          </div>
          <h1 className="display">{cat.name[lang].split(' ')[0]}{cat.name[lang].includes(' ') ? <><br/><em>{cat.name[lang].split(' ').slice(1).join(' ')}</em></> : ''}</h1>
          <p>{cat.one[lang]}</p>
          <div className="meta">
            {cat.noteAge && (
              <div className="meta-item"><div className="k">{lang === 'en' ? 'Min. age' : 'الحد الأدنى للسن'}</div><div className="v">{cat.noteAge}</div></div>
            )}
            <div className="meta-item">
              <div className="k">{lang === 'en' ? 'Availability' : 'التوفر'}</div>
              <div className="v">{cat.meta[lang]}</div>
            </div>
            <div className="meta-item">
              <div className="k">{lang === 'en' ? 'Rates' : 'الأسعار'}</div>
              <div className="v">{lang === 'en' ? 'On request' : 'حسب الطلب'}</div>
            </div>
          </div>
          <div className="hero-ctas" style={{ marginTop: 8 }}>
            <button className="btn btn-primary" onClick={() => onEnquire(cat)}>
              {lang === 'en' ? 'Request a quote' : 'اطلب عرض سعر'} <ArrowSmart s={14}/>
            </button>
            <a className="btn btn-ghost" style={{ color: 'var(--paper)' }} href={window.BENO.contact.waUrl('Hi Beno, I\u2019d like to enquire about ' + cat.name.en)} target="_blank" rel="noreferrer">
              <WAIcon s={14}/> WhatsApp
            </a>
          </div>
        </div>
      </section>

      <section className="cat-process">
        {process.map(s => (
          <div key={s.n} className="step">
            <div className="num">{s.n}</div>
            <h4>{s.t[lang]}</h4>
            <p>{s.s[lang]}</p>
          </div>
        ))}
      </section>

      {fleet.length > 0 && (
        <section className="section wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow">{lang === 'en' ? 'A glimpse of the inventory' : 'لمحة عن الأسطول'}</div>
              <h2 className="display">{lang === 'en' ? 'Recent' : 'مختارات'} <em>{cat.name[lang].toLowerCase()}</em></h2>
            </div>
            <p className="lede">
              {lang === 'en'
                ? 'Inventory is partner-supplied and changes weekly. Specific models, lengths and availability are confirmed at enquiry — no fixed catalogue.'
                : 'الأسطول من شركاء معتمدين ويتغير أسبوعيًا. تأكيد الموديل والتوفر يتم عند الاستفسار.'}
            </p>
            <button className="btn btn-ghost" style={{ color: 'var(--ink)' }} onClick={() => onEnquire(cat)}>
              {lang === 'en' ? 'Enquire' : 'استفسر'} <ArrowSmart s={12}/>
            </button>
          </div>
          <div className="fleet-grid">
            {fleet.map(f => (
              <article key={f.id} className="fleet-card" onClick={() => onEnquire({ ...cat, prefill: f.name })}>
                <div className="img-wrap">
                  <img className="img" src={f.img} alt={f.name} loading="lazy"/>
                </div>
                <span className="tag">{f.tag}</span>
                <div className="body">
                  <div className="row1">
                    <h4>{f.name}</h4>
                  </div>
                  <div className="ftr">
                    <div className="rate">
                      <div className="req">{lang === 'en' ? 'From' : 'يبدأ من'}</div>
                      <strong>{lang === 'en' ? 'On request' : 'حسب الطلب'}</strong>
                    </div>
                    <span className="btn btn-sm" style={{ background: 'var(--noir)', color: 'var(--paper)', textTransform: 'none', letterSpacing: 0, fontSize: 12 }}>
                      {lang === 'en' ? 'Enquire' : 'استفسر'} <ArrowSmart s={11}/>
                    </span>
                  </div>
                </div>
              </article>
            ))}
          </div>
        </section>
      )}

      <ConciergeBand lang={lang} onEnquire={onEnquire}/>

      {/* Related categories */}
      <section className="section wrap" style={{ paddingTop: 0 }}>
        <div className="section-head">
          <div>
            <div className="eyebrow">{lang === 'en' ? 'Or explore' : 'أو استكشف'}</div>
            <h2 className="display">{lang === 'en' ? 'Other ' : 'فئات '}<em>{lang === 'en' ? 'categories' : 'أخرى'}</em></h2>
          </div>
        </div>
        <div className="cat-grid">
          {window.BENO.categories.filter(c => c.id !== cat.id).slice(0, 3).map(c => (
            <article key={c.id} className="cat-card span-third" onClick={() => { window.scrollTo(0, 0); onCategory(c.id); }}>
              <div className="img" style={{ backgroundImage: `url(${c.img})`, aspectRatio: '4/3' }}/>
              <div className="pill">{c.pill[lang]}</div>
              <div className="corner"><ArrowSmart s={14}/></div>
              <div className="body">
                <h3>{c.name[lang]}</h3>
                <p>{c.one[lang]}</p>
              </div>
            </article>
          ))}
        </div>
      </section>
    </div>
  );
};

/* ===========================  ENQUIRY MODAL  =========================== */

const EnquiryModal = ({ open, onClose, lang, seedCategory, seedMessage }) => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    category: seedCategory?.id || '',
    occasion: '',
    date: '',
    guests: 4,
    duration: '',
    name: '',
    phone: '+971 ',
    email: '',
    message: seedMessage || (seedCategory?.prefill ? 'Interested in ' + seedCategory.prefill : ''),
  });

  React.useEffect(() => {
    if (open) {
      setStep(0);
      setData(d => ({
        ...d,
        category: seedCategory?.id || '',
        message: seedMessage || (seedCategory?.prefill ? 'Interested in ' + seedCategory.prefill : ''),
      }));
    }
  }, [open, seedCategory, seedMessage]);

  if (!open) return null;

  const T = window.BENO.copy[lang];
  const cats = window.BENO.categories;
  const occasions = lang === 'en'
    ? ['Personal day', 'Couple / anniversary', 'Family', 'Friends weekend', 'Proposal', 'Corporate / activation']
    : ['يوم شخصي', 'ذكرى زواج', 'عائلية', 'عطلة أصدقاء', 'طلب يد', 'فعالية شركة'];
  const durations = lang === 'en'
    ? ['Half day', 'Full day', 'Weekend', 'Multi-day', 'Monthly']
    : ['نصف يوم', 'يوم كامل', 'عطلة أسبوع', 'عدة أيام', 'شهري'];

  const steps = lang === 'en'
    ? ['What\u2019s the category?', 'When and how many?', 'Your details', 'Brief & handoff']
    : ['اختر الفئة', 'متى وكم؟', 'بياناتك', 'الملخص'];

  const heroImg = (cats.find(c => c.id === data.category)?.lifestyle) || 'media/lifestyle-yachts.webp';

  const canNext = () => {
    if (step === 0) return !!data.category;
    if (step === 1) return !!data.date && !!data.duration;
    if (step === 2) return data.name && data.phone && data.email;
    return true;
  };

  const next = () => setStep(s => Math.min(s + 1, 3));
  const prev = () => setStep(s => Math.max(s - 1, 0));

  const cat = cats.find(c => c.id === data.category);
  const summaryMessage = (lang === 'en'
    ? `Hi Beno, I\u2019d like to enquire about ${cat?.name.en || 'a luxury rental'}.`
    : `مرحبًا بينو، أرغب بالاستفسار عن ${cat?.name.ar || 'تأجير فاخر'}.`)
    + (data.date ? ` ${lang === 'en' ? 'Date' : 'التاريخ'}: ${data.date}.` : '')
    + (data.duration ? ` ${lang === 'en' ? 'Duration' : 'المدة'}: ${data.duration}.` : '')
    + (data.guests ? ` ${lang === 'en' ? 'Guests' : 'الضيوف'}: ${data.guests}.` : '')
    + (data.occasion ? ` ${lang === 'en' ? 'Occasion' : 'المناسبة'}: ${data.occasion}.` : '')
    + (data.message ? ` ${data.message}` : '');

  return (
    <div className="modal-scrim" onClick={e => { if (e.target.classList.contains('modal-scrim')) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <aside className="modal-aside" style={{ backgroundImage: `url(${heroImg})` }}>
          <div>
            <div className="mark" style={{ marginBottom: 18 }}>
              <Logo mono/>
            </div>
            <div className="eyebrow eyebrow-light" style={{ marginBottom: 8 }}>
              {lang === 'en' ? 'Concierge brief' : 'ملخص الكونسيرج'}
            </div>
            <h3>{lang === 'en' ? <>Tell us what you have <em>in mind.</em></> : <>أخبرنا <em>بفكرتك.</em></>}</h3>
          </div>
          <div className="steps">
            {steps.map((s, i) => (
              <div key={i} className={'step ' + (i === step ? 'active' : i < step ? 'done' : '')}>
                <span className="n">0{i + 1}</span>
                <span>{s}</span>
              </div>
            ))}
          </div>
        </aside>

        <div className="modal-body">
          <button className="close" onClick={onClose} aria-label="Close"><CloseIcon/></button>

          {step === 0 && (
            <div className="step-content view-enter">
              <h2 className="display">{lang === 'en' ? <>What are you renting <em>today?</em></> : <><em>ما الذي</em> تستأجره اليوم؟</>}</h2>
              <p className="sub">{lang === 'en' ? 'Pick a category — we\u2019ll tailor the brief.' : 'اختر فئة وسنخصص الباقي.'}</p>
              <div className="opt-grid">
                {cats.map(c => (
                  <button key={c.id} className="opt" aria-pressed={data.category === c.id} onClick={() => setData({ ...data, category: c.id })}>
                    <div className="t">{c.name[lang]}</div>
                    <div className="s">{c.pill[lang]}</div>
                  </button>
                ))}
              </div>
            </div>
          )}

          {step === 1 && (
            <div className="step-content view-enter">
              <h2 className="display">{lang === 'en' ? <>When and <em>how many?</em></> : <>متى <em>وكم؟</em></>}</h2>
              <p className="sub">{lang === 'en' ? 'We confirm live availability within the hour.' : 'نؤكد التوفر خلال ساعة.'}</p>
              <div className="field-row">
                <div className="field">
                  <label>{lang === 'en' ? 'Start date' : 'تاريخ البدء'}</label>
                  <input type="date" value={data.date} onChange={e => setData({ ...data, date: e.target.value })}/>
                </div>
                <div className="field">
                  <label>{lang === 'en' ? 'Duration' : 'المدة'}</label>
                  <select value={data.duration} onChange={e => setData({ ...data, duration: e.target.value })}>
                    <option value="">{lang === 'en' ? 'Choose…' : 'اختر…'}</option>
                    {durations.map(d => <option key={d}>{d}</option>)}
                  </select>
                </div>
              </div>
              <div className="field">
                <label>{lang === 'en' ? 'Guests' : 'عدد الضيوف'} · {data.guests}</label>
                <input type="range" min="1" max="50" value={data.guests} onChange={e => setData({ ...data, guests: Number(e.target.value) })}/>
              </div>
              <div className="field">
                <label>{lang === 'en' ? 'Occasion (optional)' : 'المناسبة (اختياري)'}</label>
                <div className="opt-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
                  {occasions.map(o => (
                    <button key={o} className="opt" aria-pressed={data.occasion === o} onClick={() => setData({ ...data, occasion: o })} style={{ padding: 10 }}>
                      <div className="t" style={{ fontSize: 14, fontFamily: 'var(--font-body)' }}>{o}</div>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="step-content view-enter">
              <h2 className="display">{lang === 'en' ? <>How can we <em>reach you?</em></> : <>كيف <em>نتواصل معك؟</em></>}</h2>
              <p className="sub">{lang === 'en' ? 'WhatsApp is fastest — we reply within the hour.' : 'الواتساب أسرع — نرد خلال ساعة.'}</p>
              <div className="field">
                <label>{lang === 'en' ? 'Full name' : 'الاسم الكامل'}</label>
                <input value={data.name} onChange={e => setData({ ...data, name: e.target.value })} placeholder={lang === 'en' ? 'e.g. Maya Hassan' : 'مايا حسن'}/>
              </div>
              <div className="field-row">
                <div className="field">
                  <label>{lang === 'en' ? 'WhatsApp / phone' : 'الواتساب / الهاتف'}</label>
                  <input value={data.phone} onChange={e => setData({ ...data, phone: e.target.value })}/>
                </div>
                <div className="field">
                  <label>Email</label>
                  <input type="email" value={data.email} onChange={e => setData({ ...data, email: e.target.value })} placeholder="you@email.com"/>
                </div>
              </div>
              <div className="field">
                <label>{lang === 'en' ? 'A sentence on what you have in mind' : 'اكتب فكرتك بجملة'}</label>
                <textarea rows="3" value={data.message} onChange={e => setData({ ...data, message: e.target.value })} placeholder={lang === 'en' ? 'e.g. \u201cYacht day for 8 next Saturday, Marina launch, sunset return.\u201d' : 'مثلاً: «يوم يخت لـ ٨ ضيوف السبت، انطلاق من المرسى، عودة عند الغروب».'}/>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="step-content view-enter handoff">
              <h2 className="display">{lang === 'en' ? <>Brief is <em>ready.</em></> : <>الملخص <em>جاهز.</em></>}</h2>
              <p className="sub">
                {lang === 'en'
                  ? 'We\u2019ve drafted your message. Send to WhatsApp for the fastest reply, or email it to reservations@beno.com.'
                  : 'حضّرنا رسالتك. أرسلها على واتساب لردّ أسرع، أو بالبريد إلى reservations@beno.com.'}
              </p>
              <div className="phone">
                <div className="topbar"><span>WhatsApp · {window.BENO.contact.whatsapp}</span><span>now</span></div>
                <div className="who">
                  <div className="av">B</div>
                  <div>
                    <div className="name">Beno Concierge</div>
                    <div className="sub">{lang === 'en' ? 'Typically replies in ~3 min' : 'يرد خلال ٣ دقائق'}</div>
                  </div>
                </div>
                <div className="msg">
                  {summaryMessage}
                  <div className="meta">{data.name ? data.name + ' · ' : ''}{data.phone || ''}</div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap', marginTop: 8 }}>
                <a className="btn" style={{ background: '#25D366', color: '#0a0a0a' }} href={window.BENO.contact.waUrl(summaryMessage)} target="_blank" rel="noreferrer">
                  <WAIcon s={14}/> {lang === 'en' ? 'Send via WhatsApp' : 'إرسال عبر واتساب'}
                </a>
                <a className="btn btn-dark" href={'mailto:' + window.BENO.contact.email + '?subject=' + encodeURIComponent('Concierge brief') + '&body=' + encodeURIComponent(summaryMessage)}>
                  ✉ {lang === 'en' ? 'Email reservations' : 'بريد الحجوزات'}
                </a>
                <a className="btn btn-ghost" style={{ color: 'var(--ink)' }} href={'tel:' + window.BENO.contact.officeTel}>
                  <PhoneIcon s={14}/> {lang === 'en' ? 'Call concierge' : 'اتصل بالكونسيرج'}
                </a>
              </div>
              <p style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'center', marginTop: 8 }}>
                {lang === 'en'
                  ? 'Routed to reservations@beno.com · CRM webhook · 24/7'
                  : 'يُحال إلى reservations@beno.com · ٢٤/٧'}
              </p>
            </div>
          )}

          <div className="modal-foot">
            <div className="progress">{lang === 'en' ? 'Step' : 'خطوة'} {step + 1} / 4</div>
            <div className="actions">
              {step > 0 && step < 3 && (
                <button className="btn btn-ghost" style={{ color: 'var(--ink)' }} onClick={prev}>
                  {lang === 'en' ? '← Back' : '→ السابق'}
                </button>
              )}
              {step < 3 && (
                <button className="btn btn-solid-teal" disabled={!canNext()} onClick={next}
                        style={!canNext() ? { opacity: .4, cursor: 'not-allowed' } : null}>
                  {step === 2 ? (lang === 'en' ? 'Review brief' : 'مراجعة الملخص') : (lang === 'en' ? 'Continue' : 'متابعة')} <ArrowSmart s={12}/>
                </button>
              )}
              {step === 3 && (
                <button className="btn btn-dark" onClick={onClose}>
                  {lang === 'en' ? 'Done' : 'تم'}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { CategoryView, EnquiryModal });
