// Mobile nav drawer — ported 1:1 from src/components/MobileNav.tsx.
(function () {
  const { useState, useRef } = React;
  const D = window.REA_DATA;
  function formatFileSize(bytes) {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  }

  function MobileNav({ isOpen, onClose }) {
    const [expandedSection, setExpandedSection] = useState(null);
    const [expandedCategory, setExpandedCategory] = useState(null);
    const [productQuery, setProductQuery] = useState('');
    const [name, setName] = useState('');
    const [phone, setPhone] = useState('');
    const [subject, setSubject] = useState(D.subjects[0]);
    const [message, setMessage] = useState('');
    const [file, setFile] = useState(null);
    const [fileError, setFileError] = useState(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isSubmitted, setIsSubmitted] = useState(false);
    const fileInputRef = useRef(null);
    if (!isOpen) return null;
    const toggleSection = (section) => {
      if (expandedSection === section) { setExpandedSection(null); }
      else { setExpandedSection(section); setExpandedCategory(null); }
    };
    const validateAndSetFile = (selected) => {
      setFileError(null);
      if (!selected) { setFile(null); return; }
      const ext = (selected.name.split('.').pop() || '').toLowerCase();
      if (!D.ACCEPTED_EXTENSIONS.includes(ext)) { setFileError('Format nepermis.'); return; }
      if (selected.size > D.MAX_SIZE_MB * 1024 * 1024) { setFileError('Fișier prea mare (>10MB).'); return; }
      setFile(selected);
    };
    const handleContactSubmit = (e) => { e.preventDefault(); setIsSubmitting(true); setTimeout(() => { setIsSubmitting(false); setIsSubmitted(true); }, 900); };
    const sectionBtn = (label, key) => (
      <button onClick={() => toggleSection(key)} className="w-full flex items-center justify-between text-base font-semibold text-foreground hover:text-primary transition-colors">
        {label}
        <Icon name="chevron-down" className={`w-5 h-5 transition-transform ${expandedSection === key ? 'rotate-180 text-primary' : 'text-muted-foreground'}`} />
      </button>
    );

    return (
      <div className="xl:hidden border-t border-border bg-background px-4 py-2 pb-8 overflow-y-auto max-h-[calc(100vh-80px)]">
        <nav className="flex flex-col divide-y divide-border">
          {/* PRODUSE */}
          <div className="py-3">
            {sectionBtn('Produse', 'produse')}
            {expandedSection === 'produse' && (
              <div className="mt-4 pl-2 space-y-4">
                <div className="relative">
                  <Icon name="search" className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
                  <input type="text" value={productQuery} onChange={(e) => setProductQuery(e.target.value)} placeholder="Caută produse..." className="w-full bg-muted/60 border border-border rounded-sm pl-9 pr-3 py-2 text-sm focus:outline-none focus:border-accent" />
                </div>
                <div className="space-y-2">
                  {D.productCategories.map((cat) => {
                    const isCatExpanded = expandedCategory === cat.slug;
                    const q = productQuery.toLowerCase();
                    const filteredItems = q ? cat.items.filter((i) => i.toLowerCase().includes(q) || cat.title.toLowerCase().includes(q)) : cat.items;
                    if (q && filteredItems.length === 0) return null;
                    return (
                      <div key={cat.slug} className="border border-border rounded-sm overflow-hidden">
                        <button onClick={() => setExpandedCategory(isCatExpanded ? null : cat.slug)} className={`w-full flex items-center gap-3 px-3 py-2.5 text-left transition-colors ${isCatExpanded ? 'bg-muted/50' : 'bg-card'}`}>
                          <img src={`../../assets/category-icons/${cat.slug}.svg`} alt="" aria-hidden="true" className="w-7 h-7 flex-shrink-0 object-contain" loading="lazy" />
                          <span className={`text-sm font-semibold flex-grow ${isCatExpanded ? 'text-primary' : 'text-foreground/80'}`}>{cat.title}</span>
                          <Icon name="chevron-down" className={`w-4 h-4 flex-shrink-0 transition-transform ${isCatExpanded ? 'rotate-180 text-primary' : 'text-muted-foreground'}`} />
                        </button>
                        {isCatExpanded && (
                          <ul className="bg-muted/20 px-3 py-2 space-y-1 border-t border-border">
                            {filteredItems.map((item) => (
                              <li key={item}><a href={D.linkForItem(item)} onClick={onClose} className="block py-1.5 text-sm text-foreground/70 hover:text-accent pl-7">{item}</a></li>
                            ))}
                            {cat.href && cat.href !== '#' && (
                              <li className="pt-1 mt-1 border-t border-border"><a href={cat.href} onClick={onClose} className="inline-flex items-center gap-1.5 py-1.5 pl-7 text-sm font-semibold text-accent">Vezi toată gama <Icon name="arrow-right" className="w-3.5 h-3.5" /></a></li>
                            )}
                          </ul>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
          {/* SERVICII */}
          <div className="py-3">
            {sectionBtn('Servicii', 'servicii')}
            {expandedSection === 'servicii' && (
              <div className="mt-4 pl-2 space-y-2">
                {D.services.map((service) => (
                  <a key={service.slug} href={D.linkForItem(service.title)} onClick={onClose} className="flex items-start gap-3 p-3 border border-border rounded-sm bg-card">
                    <div className="w-20 h-16 rounded-sm overflow-hidden bg-muted flex-shrink-0">
                      <img src={service.image} alt={service.title} className="w-full h-full object-cover" loading="lazy" />
                    </div>
                    <div className="min-w-0">
                      <div className="text-sm font-bold text-primary mb-0.5">{service.title}</div>
                      <div className="text-xs text-foreground/70 leading-snug">{service.description}</div>
                    </div>
                  </a>
                ))}
                <a href="../servicii/index.html" onClick={onClose} className="inline-flex items-center gap-2 pt-1 pl-1 text-sm font-semibold text-accent">Vezi toate serviciile <Icon name="arrow-right" className="w-4 h-4" /></a>
              </div>
            )}
          </div>
          {/* PARTENERI */}
          <div className="py-3">
            {sectionBtn('Parteneri', 'parteneri')}
            {expandedSection === 'parteneri' && (
              <div className="mt-4 pl-2 space-y-4">
                <div className="grid grid-cols-1 gap-2">
                  {D.partners.map((partner) => (
                    <a key={partner.name} href={partner.href || '../parteneri/index.html'} onClick={onClose} className="group flex flex-col p-4 border border-border rounded-sm bg-card hover:bg-muted/40 transition-colors">
                      <div className="flex items-start gap-3 mb-3 min-h-[40px]">
                        <img src={partner.logo} alt={`${partner.name} logo`} className={`${partner.cardLogoHeightClass || 'h-10'} w-auto object-contain opacity-90 group-hover:opacity-100 transition-opacity`} loading="lazy" />
                      </div>
                      <p className="text-xs text-foreground/70 leading-snug">{partner.specialty}</p>
                    </a>
                  ))}
                </div>
                <a href="../parteneri/index.html" onClick={onClose} className="inline-flex items-center gap-2 text-sm font-semibold text-accent">Vezi toți partenerii <Icon name="arrow-right" className="w-4 h-4" /></a>
              </div>
            )}
          </div>
          {/* DESPRE */}
          <div className="py-3">
            {sectionBtn('Despre', 'despre')}
            {expandedSection === 'despre' && (
              <div className="mt-4 pl-2 space-y-4">
                <div>
                  <h4 className="font-headings text-base font-bold text-primary leading-tight">Partener tehnic pentru industria românească din 1994</h4>
                </div>
                <p className="text-sm text-foreground/70 leading-relaxed">Importăm și distribuim echipamente industriale pentru sisteme abur-condens, armături, instrumentație și pneumatică. Reprezentăm exclusiv 9 producători din Europa și SUA. Servim rafinării, combinate chimice, energie, farmaceutică și alte 7 industrii grele.</p>
                <div className="grid grid-cols-2 gap-2">
                  {D.aboutStats.map((s) => (
                    <div key={s.label} className="bg-muted/40 border border-border p-3 rounded-sm">
                      <div className="text-lg font-bold text-primary">{s.value}</div>
                      <div className="text-[10px] font-semibold tracking-wider text-muted-foreground uppercase">{s.label}</div>
                    </div>
                  ))}
                </div>
                <a href="../companie/index.html" onClick={onClose} className="inline-flex items-center gap-2 text-sm font-semibold text-accent">Vezi povestea completă <Icon name="arrow-right" className="w-4 h-4" /></a>
              </div>
            )}
          </div>
          {/* CARIERE */}
          <div className="py-3">
            {sectionBtn('Cariere', 'cariere')}
            {expandedSection === 'cariere' && (
              <div className="mt-4 pl-2 space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-px bg-border border border-border rounded-sm overflow-hidden">
                  {D.values.map((v) => (
                    <div key={v.title} className="bg-card p-3 flex flex-col">
                      <div className="flex items-center gap-2 mb-2">
                        <Icon name={v.icon} className="w-3.5 h-3.5 text-accent flex-shrink-0" />
                        <span className="text-[10px] font-bold tracking-[0.2em] text-muted-foreground uppercase leading-tight">{v.title}</span>
                      </div>
                      <span className="font-headings text-xl font-bold text-primary leading-none mb-1">{v.stat}</span>
                      <span className="text-xs text-foreground/70 leading-snug">{v.statLabel}</span>
                    </div>
                  ))}
                </div>
                <div className="border border-border rounded-sm divide-y divide-border">
                  {D.openPositions.map((p) => (
                    <a key={p.title} href="#" onClick={onClose} className="block p-3 hover:bg-muted/40">
                      <div className="text-sm font-bold text-primary mb-0.5">{p.title}</div>
                      <div className="flex items-center gap-3 text-xs text-muted-foreground">
                        <span className="uppercase tracking-wider font-semibold flex-grow min-w-0 truncate">{p.department}</span>
                        <span className="flex items-center gap-1 flex-shrink-0 min-w-[5.5rem]"><Icon name="map-pin" className="w-3 h-3 flex-shrink-0" /> {p.location}</span>
                      </div>
                    </a>
                  ))}
                </div>
                <a href="../cariere/index.html" onClick={onClose} className="inline-flex items-center gap-2 text-sm font-semibold text-accent">Vezi toate pozițiile <Icon name="arrow-right" className="w-4 h-4" /></a>
              </div>
            )}
          </div>
          {/* CONTACT */}
          <div className="py-3">
            {sectionBtn('Contact', 'contact')}
            {expandedSection === 'contact' && (
              <div className="mt-4 pl-2 space-y-6">
                <div className="bg-muted/40 border border-border rounded-sm p-4 space-y-4">
                  <a href="tel:+40212323884" className="flex items-start gap-3 group">
                    <Icon name="phone" className="w-4 h-4 text-accent flex-shrink-0 mt-0.5" strokeWidth={2} />
                    <div>
                      <div className="text-xs font-semibold tracking-[0.2em] text-muted-foreground uppercase">Telefon</div>
                      <div className="text-sm font-semibold text-foreground">+40 21 232 38 84</div>
                    </div>
                  </a>
                  <a href="tel:+40722402902" className="flex items-start gap-3 group">
                    <Icon name="smartphone" className="w-4 h-4 text-accent flex-shrink-0 mt-0.5" strokeWidth={2} />
                    <div>
                      <div className="text-xs font-semibold tracking-[0.2em] text-muted-foreground uppercase">Mobil</div>
                      <div className="text-sm font-semibold text-foreground">+40 722 402 902</div>
                    </div>
                  </a>
                  <a href="mailto:rea@romenergy.ro" className="flex items-start gap-3 group">
                    <Icon name="mail" className="w-4 h-4 text-accent flex-shrink-0 mt-0.5" strokeWidth={2} />
                    <div className="min-w-0">
                      <div className="text-xs font-semibold tracking-[0.2em] text-muted-foreground uppercase">Email</div>
                      <div className="text-sm font-semibold text-foreground truncate">rea@romenergy.ro</div>
                    </div>
                  </a>
                  <div className="flex items-start gap-3">
                    <Icon name="map-pin" className="w-4 h-4 text-accent flex-shrink-0 mt-0.5" strokeWidth={2} />
                    <div>
                      <div className="text-xs font-semibold tracking-[0.2em] text-muted-foreground uppercase">Sediu</div>
                      <div className="text-sm text-foreground/80 leading-snug">Str. Avram Iancu 25<br />Otopeni, Ilfov 075100</div>
                    </div>
                  </div>
                  <div className="flex items-start gap-3">
                    <Icon name="clock" className="w-4 h-4 text-accent flex-shrink-0 mt-0.5" strokeWidth={2} />
                    <div>
                      <div className="text-xs font-semibold tracking-[0.2em] text-muted-foreground uppercase">Program</div>
                      <div className="text-sm text-foreground/80">Luni–Vineri <span className="font-normal text-foreground">09:00-18:00</span></div>
                    </div>
                  </div>
                </div>
                <a href="https://www.google.com/maps/search/?api=1&query=Str.+Avram+Iancu+25,+Otopeni,+Ilfov+075100"
                  target="_blank" rel="noreferrer"
                  className="group relative block h-40 rounded-sm overflow-hidden border border-border">
                  <iframe
                    title="Hartă sediu Rom Energy Armstrong — Str. Avram Iancu 25, Otopeni"
                    src="https://www.google.com/maps?q=Str.%20Avram%20Iancu%2025,%20Otopeni,%20Ilfov%20075100&z=14&output=embed"
                    className="absolute inset-0 w-full h-full grayscale-[0.2] pointer-events-none"
                    style={{ border: 0 }} loading="lazy" referrerPolicy="no-referrer-when-downgrade" aria-hidden="true"></iframe>
                </a>
                <a href="../contact/index.html" onClick={onClose} className="inline-flex items-center gap-2 text-sm font-semibold text-accent">Vezi pagina completă de Contact <Icon name="arrow-right" className="w-4 h-4" /></a>
                <div className="border-t border-border pt-4">
                  <h4 className="text-sm font-bold text-primary mb-3">Trimite o cerere</h4>
                  {isSubmitted ? (
                    <div className="border border-border rounded-sm p-4 bg-muted/40 flex items-start gap-3">
                      <Icon name="check-circle" className="w-5 h-5 text-accent flex-shrink-0" />
                      <div className="text-sm text-foreground/80">Cerere trimisă. Te contactăm în max 24h.</div>
                    </div>
                  ) : (
                    <form onSubmit={handleContactSubmit} className="space-y-3">
                      <input type="text" value={name} onChange={(e) => setName(e.target.value)} required placeholder="Nume și prenume" className="w-full bg-muted/60 border border-border rounded-sm px-3 py-2 text-sm focus:border-accent focus:outline-none" />
                      <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} required placeholder="Telefon" className="w-full bg-muted/60 border border-border rounded-sm px-3 py-2 text-sm focus:border-accent focus:outline-none" />
                      <select value={subject} onChange={(e) => setSubject(e.target.value)} className="w-full bg-muted/60 border border-border rounded-sm px-3 py-2 text-sm focus:border-accent focus:outline-none">
                        {D.subjects.map((s) => <option key={s} value={s}>{s}</option>)}
                      </select>
                      <textarea value={message} onChange={(e) => setMessage(e.target.value)} required rows={2} placeholder="Mesaj scurt..." className="w-full bg-muted/60 border border-border rounded-sm px-3 py-2 text-sm focus:border-accent focus:outline-none resize-none" />
                      <div>
                        <input ref={fileInputRef} type="file" onChange={(e) => validateAndSetFile(e.target.files && e.target.files[0] || null)} className="hidden" />
                        {!file ? (
                          <button type="button" onClick={() => fileInputRef.current && fileInputRef.current.click()} className="w-full flex items-center justify-center gap-2 px-3 py-2 border border-dashed border-border rounded-sm text-sm text-muted-foreground hover:bg-muted/50">
                            <Icon name="paperclip" className="w-4 h-4" /> Atașează fișier (opțional)
                          </button>
                        ) : (
                          <div className="flex items-center justify-between px-3 py-2 border border-border bg-muted/40 rounded-sm text-sm">
                            <span className="truncate pr-2">{file.name}</span>
                            <button type="button" onClick={() => setFile(null)} className="text-muted-foreground"><Icon name="x" className="w-4 h-4" /></button>
                          </div>
                        )}
                        {fileError && <div className="text-xs text-destructive mt-1">{fileError}</div>}
                      </div>
                      <button type="submit" disabled={isSubmitting} className="w-full bg-accent text-accent-foreground py-2.5 rounded-sm font-semibold text-sm flex justify-center items-center gap-2">
                        {isSubmitting ? 'Se trimite...' : 'Trimite cererea'}
                      </button>
                    </form>
                  )}
                </div>
              </div>
            )}
          </div>
        </nav>
      </div>
    );
  }

  window.MobileNav = MobileNav;
})();
