// Trend Home — unit detail panel + contact form

// ─────────────────────────────────────────────────────────────────
// UNIT DETAIL — slide-up overlay with floorplan, gallery, summary, CTA
// ─────────────────────────────────────────────────────────────────
function UnitDetail({ unit, onClose, onRequestVisit }) {
  const [tab, setTab] = React.useState('plani');
  const [galleryIdx, setGalleryIdx] = React.useState(0);
  const u = unit || TH_FEATURED_UNIT;

  React.useEffect(() => {
    if (!unit) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [unit, onClose]);

  if (!unit) return null;

  return (
    <div className="th-detail" role="dialog" aria-modal="true">
      <div className="th-detail__backdrop" onClick={onClose} />
      <aside className="th-detail__panel">
        <header className="th-detail__head">
          <div>
            <span className="th-eyebrow"><span className="th-dot" /> {u.building || 'Kompleksi Kristal · Kulla 2B'}</span>
            <h3 className="th-detail__title">Banesa <em>{u.id}</em> · {u.type}</h3>
            <p className="th-detail__sub">Kati {u.floor} · {u.orientation} · Dorëzim {u.delivery || 'Q3 2026'}</p>
          </div>
          <button className="th-detail__close" onClick={onClose} aria-label="Mbyll">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
          </button>
        </header>

        <div className="th-detail__price">
          <div>
            <div className="th-detail__priceMain">{fmtEUR(u.price)}</div>
            <div className="th-detail__pricePer">{fmtEUR(Math.round(u.price / u.m2))} / m²</div>
          </div>
          <div className="th-detail__keyfacts">
            <div><strong>{fmtM2(u.m2)}</strong><span>Sipërfaqe bruto</span></div>
            <div><strong>{u.bedrooms}</strong><span>Dhoma gjumi</span></div>
            <div><strong>{u.baths}</strong><span>Banjo</span></div>
            <div><strong>{u.balconies}</strong><span>Terasa</span></div>
          </div>
        </div>

        <div className="th-detail__tabs">
          {[['plani', 'Plani'], ['galeri', 'Galeria'], ['dhomat', 'Dhomat'], ['perfshira', 'Çfarë përfshihet']].map(([k, l]) => (
            <button key={k} className={`th-tab ${tab === k ? 'th-tab--active' : ''}`} onClick={() => setTab(k)}>{l}</button>
          ))}
        </div>

        <div className="th-detail__body">
          {tab === 'plani' && (
            <div className="th-detail__plan">
              <div className="th-detail__planImg">
                <img src={u.planImg || 'uploads/img7.jpg'} alt="Plani i banesës" />
                <div className="th-detail__planTag">Plani teknik · {fmtM2(u.m2)}</div>
              </div>
              <div className="th-detail__planFacts">
                <div className="th-fact"><span>Sipërfaqe bruto</span><strong>{fmtM2(u.m2)}</strong></div>
                <div className="th-fact"><span>Sipërfaqe neto</span><strong>{fmtM2(u.netM2 || u.m2 * 0.86)}</strong></div>
                <div className="th-fact"><span>Orientimi</span><strong>{u.orientation}</strong></div>
                <div className="th-fact"><span>Parkim</span><strong>{u.parking || 1} vend</strong></div>
                <div className="th-fact"><span>Tipi</span><strong>{u.type}</strong></div>
                <div className="th-fact"><span>Dorëzim</span><strong>{u.delivery || 'Q3 2026'}</strong></div>
              </div>
            </div>
          )}

          {tab === 'galeri' && (
            <div className="th-detail__gallery">
              <div className="th-detail__galleryMain">
                <img src={u.gallery?.[galleryIdx] || TH_FEATURED_UNIT.gallery[galleryIdx]} alt="" />
              </div>
              <div className="th-detail__galleryThumbs">
                {(u.gallery || TH_FEATURED_UNIT.gallery).map((src, i) => (
                  <button key={i} className={`th-thumb ${i === galleryIdx ? 'th-thumb--active' : ''}`} onClick={() => setGalleryIdx(i)}>
                    <img src={src} alt="" />
                  </button>
                ))}
              </div>
            </div>
          )}

          {tab === 'dhomat' && (
            <ul className="th-detail__rooms">
              {(u.rooms || TH_FEATURED_UNIT.rooms).map((r) => (
                <li key={r.name}>
                  <span>{r.name}</span>
                  <span className="th-detail__roomDots" aria-hidden />
                  <strong>{fmtM2(r.m2)}</strong>
                </li>
              ))}
            </ul>
          )}

          {tab === 'perfshira' && (
            <ul className="th-detail__amenities">
              {(u.amenities || TH_FEATURED_UNIT.amenities).map((a) => (
                <li key={a}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M20 6L9 17l-5-5"/></svg>
                  {a}
                </li>
              ))}
            </ul>
          )}
        </div>

        <footer className="th-detail__foot">
          <button className="th-btn th-btn--ghost" onClick={onClose}>Kthehu te lista</button>
          <button className="th-btn th-btn--solid th-btn--lg" onClick={onRequestVisit}>
            Cakto vizitë për {u.id}
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </button>
        </footer>
      </aside>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// CONTACT / VIEWING FORM
// ─────────────────────────────────────────────────────────────────
function ContactForm({ prefilledUnit }) {
  const [form, setForm] = React.useState({
    name: '', phone: '', email: '',
    complex: prefilledUnit ? 'kristal' : '',
    unitInterest: prefilledUnit?.id || '',
    when: 'mengjes',
    message: '',
  });
  const [sent, setSent] = React.useState(false);
  const [step, setStep] = React.useState(1);

  React.useEffect(() => {
    if (prefilledUnit) {
      setForm((f) => ({ ...f, complex: 'kristal', unitInterest: prefilledUnit.id }));
      setStep(2);
    }
  }, [prefilledUnit]);

  const upd = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const valid1 = form.complex && form.unitInterest;
  const valid2 = form.name.trim().length > 1 && (form.phone.length > 5 || form.email.includes('@'));

  const submit = (e) => {
    e.preventDefault();
    if (!valid2) return;
    setSent(true);
  };

  return (
    <section className="th-section th-contact" id="kontakt">
      <div className="th-contact__grid">
        <div className="th-contact__copy">
          <span className="th-eyebrow"><span className="th-dot" /> Cakto një vizitë</span>
          <h2 className="th-h2">Eja, shih banesën, <em>pastaj vendos.</em></h2>
          <p className="th-section__lede">
            Ekipi ynë i shitjeve do të të takojë në vendndodhje brenda 48 orëve.
            Pa zotim, pa presion. Vetëm kafe dhe pyetje.
          </p>
          <div className="th-contact__channels">
            <a href="tel:+38349807840">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><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-6 19.79 19.79 0 0 1-3.07-8.67A2 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"/></svg>
              <div>
                <span>Telefon</span>
                <strong>+383 49 807 840</strong>
              </div>
            </a>
            <a href="mailto:info@trendhome-ks.com">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 4h16c1 0 2 1 2 2v12c0 1-1 2-2 2H4c-1 0-2-1-2-2V6c0-1 1-2 2-2zM22 6l-10 7L2 6"/></svg>
              <div>
                <span>Email</span>
                <strong>info@trendhome-ks.com</strong>
              </div>
            </a>
            <a href="#">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>
              <div>
                <span>Adresa e zyrës</span>
                <strong>Rr. Mbretëresha Teutë, Pejë</strong>
              </div>
            </a>
          </div>
        </div>

        <form className="th-contact__form" onSubmit={submit}>
          {sent ? (
            <div className="th-contact__sent">
              <div className="th-contact__sentIcon">
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20 6L9 17l-5-5"/></svg>
              </div>
              <h3>Faleminderit, {form.name.split(' ')[0]}!</h3>
              <p>Kërkesa jote për vizitë në banesën <strong>{form.unitInterest}</strong> është dërguar.
              Ekipi ynë do të të kontaktojë brenda 24 orëve në numrin {form.phone || form.email}.</p>
              <button type="button" className="th-btn th-btn--ghost" onClick={() => { setSent(false); setStep(1); setForm({ name: '', phone: '', email: '', complex: '', unitInterest: '', when: 'mengjes', message: '' }); }}>
                Dërgo një tjetër
              </button>
            </div>
          ) : (
            <>
              <div className="th-contact__steps">
                <div className={`th-step ${step >= 1 ? 'th-step--active' : ''}`}>
                  <span>1</span> Banesa
                </div>
                <div className="th-step__line" />
                <div className={`th-step ${step >= 2 ? 'th-step--active' : ''}`}>
                  <span>2</span> Të dhënat
                </div>
              </div>

              {step === 1 && (
                <div className="th-contact__step">
                  <label className="th-field">
                    <span>Kompleksi</span>
                    <select value={form.complex} onChange={(e) => upd('complex', e.target.value)}>
                      <option value="">Zgjidh kompleksin…</option>
                      {TH_COMPLEXES.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                    </select>
                  </label>
                  <label className="th-field">
                    <span>Banesa me interes</span>
                    <input type="text" value={form.unitInterest}
                      placeholder="p.sh. B2-8A, ose 'akoma duke shikuar'"
                      onChange={(e) => upd('unitInterest', e.target.value)} />
                  </label>
                  <label className="th-field">
                    <span>Kur preferon të vish?</span>
                    <div className="th-radio-row">
                      {[['mengjes', 'Mëngjes'], ['drekë', 'Drekë'], ['mbremje', 'Mbrëmje'], ['fundjave', 'Fundjavë']].map(([k, l]) => (
                        <label key={k} className={`th-radio ${form.when === k ? 'th-radio--on' : ''}`}>
                          <input type="radio" name="when" value={k} checked={form.when === k} onChange={() => upd('when', k)} />
                          {l}
                        </label>
                      ))}
                    </div>
                  </label>
                  <button type="button" className="th-btn th-btn--solid th-btn--lg th-contact__next"
                    disabled={!valid1} onClick={() => setStep(2)}>
                    Vazhdo
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
                  </button>
                </div>
              )}

              {step === 2 && (
                <div className="th-contact__step">
                  <label className="th-field">
                    <span>Emri i plotë</span>
                    <input type="text" value={form.name} placeholder="Arta Krasniqi"
                      onChange={(e) => upd('name', e.target.value)} />
                  </label>
                  <div className="th-field-row">
                    <label className="th-field">
                      <span>Telefon</span>
                      <input type="tel" value={form.phone} placeholder="+383 4_ ___ ___"
                        onChange={(e) => upd('phone', e.target.value)} />
                    </label>
                    <label className="th-field">
                      <span>Email</span>
                      <input type="email" value={form.email} placeholder="ti@email.com"
                        onChange={(e) => upd('email', e.target.value)} />
                    </label>
                  </div>
                  <label className="th-field">
                    <span>Mesazh (opsional)</span>
                    <textarea rows="3" value={form.message} placeholder="Pyetje, kërkesa të veçanta…"
                      onChange={(e) => upd('message', e.target.value)} />
                  </label>
                  <div className="th-contact__actions">
                    <button type="button" className="th-btn th-btn--ghost" onClick={() => setStep(1)}>← Kthehu</button>
                    <button type="submit" className="th-btn th-btn--solid th-btn--lg" disabled={!valid2}>
                      Dërgo kërkesën
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
                    </button>
                  </div>
                  <p className="th-contact__fine">Duke dërguar, pranon politikat tona të privatësisë.</p>
                </div>
              )}
            </>
          )}
        </form>
      </div>
    </section>
  );
}

Object.assign(window, { UnitDetail, ContactForm });
