// Shared primitives — the single source of truth for repeating motifs used by
// BOTH the homepage (Sections.jsx) and the category page (CategoryPage.jsx).
// Extracted verbatim from the homepage markup so output stays pixel-identical.
//   • Eyebrow          — the accent bar + tracked uppercase kicker
//   • GridBg           — the faint blueprint grid overlay
//   • SectionHeader    — kicker + heading + description block (grid sections)
//   • CategoryCard     — image / title / description / "Vezi gama" card
//   • CategoryCardGrid — the responsive 1→4 column card grid
(function () {
  /* ----------------------------- EYEBROW ------------------------------ */
  // The accent kicker motif. `centered` adds a matching bar on the right and
  // centers the row (used by section headers that are middle-aligned).
  function Eyebrow({ label, as = 'span', centered = false, className = '' }) {
    const Tag = as;
    return (
      <div className={`flex items-center gap-3 ${centered ? 'justify-center' : ''} ${className}`}>
        <span className="block w-px h-3.5 bg-accent"></span>
        <Tag className="text-xs font-bold tracking-[0.2em] text-accent uppercase">{label}</Tag>
        {centered && <span className="block w-px h-3.5 bg-accent"></span>}
      </div>
    );
  }

  /* ----------------------------- GRID BG ------------------------------ */
  // Faint 48px blueprint grid. Default = dark on light (hero / page header);
  // pass color="#FFFFFF" opacity={0.1} for the dark CTA band.
  function GridBg({ color = '#1D2235', opacity = 0.035, fade = false }) {
    const mask = fade
      ? 'radial-gradient(ellipse 75% 70% at 50% 50%, #000 30%, transparent 80%)'
      : undefined;
    return (
      <div aria-hidden="true" className="absolute inset-0 pointer-events-none"
        style={{
          opacity,
          backgroundImage: `linear-gradient(to right, ${color} 1px, transparent 1px), linear-gradient(to bottom, ${color} 1px, transparent 1px)`,
          backgroundSize: '48px 48px',
          maskImage: mask,
          WebkitMaskImage: mask
        }} />
    );
  }

  /* --------------------------- SECTION HEADER ------------------------- */
  // Kicker + heading + optional description. `action` renders an aligned link
  // on the right (md+). Used by every "grid of cards" section.
  function SectionHeader({ kicker, title, description, action }) {
    return (
      <div className="mb-12 md:mb-16 flex flex-col md:flex-row md:items-end md:justify-between gap-6">
        <div className="max-w-2xl">
          {kicker ? <Eyebrow label={kicker} className="mb-4" /> : null}
          <h2 className="font-headings text-3xl md:text-4xl font-bold text-primary mb-4">{title}</h2>
          {description && <p className="text-lg text-foreground/70">{description}</p>}
        </div>
        {action || null}
      </div>
    );
  }

  /* --------------------------- CATEGORY CARD -------------------------- */
  // One product/sub-category tile. Falls back to a "În curând" placeholder when
  // the item has no image (sub-categories not yet shot). `cta` overrides the
  // default "Vezi gama" label.
  function CategoryCard({ item }) {
    return (
      <a href={item.href} className="group relative flex flex-col bg-card border border-border rounded-sm overflow-hidden hover:border-accent hover:shadow-md transition-all">
        <div className="relative h-56 overflow-hidden bg-muted/40 flex items-center justify-center">
          {item.image ? (
            <img src={item.image} alt={item.title} className="absolute inset-0 w-full h-full object-contain p-4 group-hover:scale-105 transition-transform duration-500 ease-out" />
          ) : (
            <div className="absolute inset-0 flex items-center justify-center"
              style={{ backgroundColor: '#EEF0F5', backgroundImage: 'repeating-linear-gradient(45deg, rgba(29,34,53,0.06) 0, rgba(29,34,53,0.06) 1px, transparent 1px, transparent 10px)' }}>
              <span className="inline-flex items-center gap-2 px-3.5 py-2 rounded-full bg-background border border-border shadow-sm text-[10px] font-bold tracking-[0.18em] uppercase text-foreground/55">
                <Icon name="clock" className="w-3.5 h-3.5 text-accent" strokeWidth={2} />
                Imagine în curând
              </span>
            </div>
          )}
        </div>
        <div className="p-5 flex flex-col flex-grow">
          <h3 className="font-headings text-lg font-bold text-primary leading-snug mb-2 group-hover:text-accent transition-colors">{item.title}</h3>
          <p className="text-sm text-foreground/70 leading-relaxed mb-5 flex-grow">{item.description}</p>
          <div className="inline-flex items-center text-xs font-semibold text-accent tracking-normal mt-auto">
            <span>{item.cta || 'Vezi gama'}</span>
            <Icon name="arrow-right" className="w-3.5 h-3.5 ml-1.5 group-hover:translate-x-1 transition-transform" />
          </div>
        </div>
      </a>
    );
  }

  /* ------------------------- CATEGORY CARD GRID ----------------------- */
  function CategoryCardGrid({ items }) {
    return (
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        {items.map((item) => <CategoryCard key={item.slug} item={item} />)}
      </div>
    );
  }

  /* ------------------------------ MODAL SHELL ------------------------ */
  // Shared centered-overlay scaffold: scroll-lock (scrollbar-width compensated),
  // ESC-to-close, click-outside, close button. Children render inside the card.
  // Both lead modals share ONE size so they read as the same surface: a near-
  // fullscreen card (small uniform margin all around) with identical width and
  // height. Content scrolls inside; the card itself never grows past the viewport.
  function ModalShell({ open, onClose, maxW = 'max-w-5xl', label, children }) {
    React.useEffect(() => {
      if (!open) return;
      const onKey = (e) => { if (e.key === 'Escape') onClose(); };
      document.addEventListener('keydown', onKey);
      const scrollbarW = window.innerWidth - document.documentElement.clientWidth;
      const prevOverflow = document.body.style.overflow;
      const prevPad = document.body.style.paddingRight;
      document.body.style.overflow = 'hidden';
      if (scrollbarW > 0) document.body.style.paddingRight = scrollbarW + 'px';
      // Signal "a modal is open" so other fixed chrome (e.g. the mobile CTA bar)
      // can hide itself — otherwise it bleeds through the blurred backdrop.
      document.documentElement.setAttribute('data-modal-open', '');
      window.dispatchEvent(new CustomEvent('rea:modal-state', { detail: { open: true } }));
      return () => {
        document.removeEventListener('keydown', onKey);
        document.body.style.overflow = prevOverflow;
        document.body.style.paddingRight = prevPad;
        document.documentElement.removeAttribute('data-modal-open');
        window.dispatchEvent(new CustomEvent('rea:modal-state', { detail: { open: false } }));
      };
    }, [open, onClose]);
    if (!open) return null;
    return (
      <div className="fixed inset-0 z-[100] flex items-stretch justify-center bg-primary/70 backdrop-blur-sm p-3 sm:p-4 lg:p-6"
        onClick={onClose} role="dialog" aria-modal="true" aria-label={label}>
        <div className={`relative w-full ${maxW} max-h-full bg-background shadow-2xl flex flex-col rounded-sm border border-border overflow-hidden`}
          onClick={(e) => e.stopPropagation()}>
          {/* Floating X — sits on the title row; titles carry right padding so they never overlap */}
          <button type="button" onClick={onClose} aria-label="Închide"
            className="absolute right-3 top-3 z-20 w-10 h-10 flex items-center justify-center rounded-sm text-foreground hover:bg-muted transition-colors">
            <Icon name="x" className="w-6 h-6" strokeWidth={2.5} />
          </button>
          <div className="flex-1 overflow-y-auto overscroll-contain">
            {children}
          </div>
        </div>
      </div>
    );
  }

  /* ----------------------------- CONTACT MODAL ----------------------- */
  // Quote-request form (reuses the mega-menu contact form, variant="modal").
  // Drive with local state: <ContactModal open={open} onClose={() => setOpen(false)} />
  function ContactModal({ open, onClose }) {
    return (
      <ModalShell open={open} onClose={onClose} label="Formular de contact">
        <MegaMenuContact variant="modal" onClose={onClose} />
      </ModalShell>
    );
  }

  /* --------------------------- CONSULT MODAL ------------------------- */
  // Technical-consultation request — a softer, application-led lead form for the
  // "I don't know what I need yet" visitor. Still a lead: framed toward an offer.
  const consultFieldCls = "w-full bg-background border border-border rounded-sm px-3 py-2.5 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent transition-colors";
  const consultLabelCls = "block text-xs font-semibold tracking-[0.18em] text-foreground/70 uppercase mb-1.5";
  const CONSULT_DOMAINS = ['Abur (cazane, distribuție)', 'Condens & recuperare căldură', 'Reducere / control presiune', 'Măsurare & control abur', 'Nu sunt sigur — am nevoie de ghidare'];
  const CONSULT_SLOTS = ['Dimineața (09:00–12:00)', 'Prânz (12:00–15:00)', 'După-amiaza (15:00–18:00)'];

  function ConsultModal({ open, onClose }) {
    const [channel, setChannel] = React.useState('call');
    const [name, setName] = React.useState('');
    const [phone, setPhone] = React.useState('');
    const [email, setEmail] = React.useState('');
    const [slot, setSlot] = React.useState(CONSULT_SLOTS[0]);
    const [domain, setDomain] = React.useState(CONSULT_DOMAINS[0]);
    const [params, setParams] = React.useState('');
    const [message, setMessage] = React.useState('');
    const [submitting, setSubmitting] = React.useState(false);
    const [submitted, setSubmitted] = React.useState(false);
    const [file, setFile] = React.useState(null);
    const [fileError, setFileError] = React.useState(null);
    const [isDragging, setIsDragging] = React.useState(false);
    const fileInputRef = React.useRef(null);
    const _D = window.REA_DATA || {};
    const ACCEPTED = _D.ACCEPTED_EXTENSIONS || ['pdf', 'docx', 'xlsx', 'dwg', 'jpg', 'jpeg', 'png'];
    const MAX_MB = _D.MAX_SIZE_MB || 10;
    const fmtSize = (b) => b < 1024 ? `${b} B` : b < 1048576 ? `${(b / 1024).toFixed(0)} KB` : `${(b / 1048576).toFixed(1)} MB`;
    const validateFile = (sel) => {
      setFileError(null);
      if (!sel) { setFile(null); return; }
      const ext = (sel.name.split('.').pop() || '').toLowerCase();
      if (!ACCEPTED.includes(ext)) { setFileError(`Format nepermis. Acceptăm: ${ACCEPTED.join(', ').toUpperCase()}`); return; }
      if (sel.size > MAX_MB * 1024 * 1024) { setFileError(`Fișierul depășește ${MAX_MB}MB.`); return; }
      setFile(sel);
    };
    const onDrop = (e) => { e.preventDefault(); setIsDragging(false); const f = e.dataTransfer.files && e.dataTransfer.files[0]; if (f) validateFile(f); };
    const handleSubmit = (e) => { e.preventDefault(); setSubmitting(true); setTimeout(() => { setSubmitting(false); setSubmitted(true); }, 900); };
    const seg = (active) => `inline-flex items-center justify-center gap-2 px-3 py-2.5 rounded-sm text-sm font-semibold border transition-colors ${active ? 'bg-accent text-accent-foreground border-accent' : 'bg-muted/40 text-foreground/70 border-border hover:border-accent/50'}`;

    return (
      <ModalShell open={open} onClose={onClose} label="Cerere de consultanță tehnică">
        <div className="container mx-auto px-4 py-8">
          {submitted ? (
            <div className="max-w-xl flex flex-col items-start">
              <span className="w-12 h-12 bg-accent/10 rounded-sm flex items-center justify-center mb-5">
                <Icon name="check-circle" className="w-6 h-6 text-accent" strokeWidth={2} />
              </span>
              <h3 className="font-headings text-2xl font-bold text-primary mb-2">Cerere trimisă</h3>
              <p className="text-sm text-foreground/70 leading-relaxed">Mulțumim, {name || 'partener'}! Un inginer te contactează în max 24h în zile lucrătoare cu o recomandare și o ofertă pentru aplicația ta.</p>
              <button type="button" onClick={onClose} className="mt-6 inline-flex items-center gap-2 bg-primary hover:bg-primary/90 text-primary-foreground px-5 py-2.5 rounded-sm font-semibold text-sm transition-colors">Închide</button>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-5 gap-6 lg:gap-10">
              <div className="md:col-span-3">
                <h3 className="font-headings text-xl font-bold text-primary leading-tight mb-2 pr-12 text-balance">Vorbește cu un inginer</h3>
                <p className="text-sm text-foreground/70 leading-relaxed mb-6">Spune-ne despre aplicația ta. Un inginer te ajută să alegi și să dimensionezi echipamentul potrivit.</p>
                <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label className={consultLabelCls}>Cum preferi să te contactăm?</label>
                  <div className="grid grid-cols-2 gap-2">
                    <button type="button" onClick={() => setChannel('call')} className={seg(channel === 'call')}>
                      <Icon name="phone" className="w-4 h-4" strokeWidth={2} />Apel
                    </button>
                    <button type="button" onClick={() => setChannel('email')} className={seg(channel === 'email')}>
                      <Icon name="mail" className="w-4 h-4" strokeWidth={2} />Email
                    </button>
                  </div>
                </div>
                <div>
                  <label htmlFor="cons-name" className={consultLabelCls}>Nume</label>
                  <input id="cons-name" type="text" required value={name} onChange={(e) => setName(e.target.value)} placeholder="Nume și prenume" className={consultFieldCls} />
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label htmlFor="cons-phone" className={consultLabelCls}>Telefon</label>
                    <input id="cons-phone" type="tel" required value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+40 7XX XXX XXX" className={consultFieldCls} />
                  </div>
                  {channel === 'email' ? (
                    <div>
                      <label htmlFor="cons-email" className={consultLabelCls}>Email</label>
                      <input id="cons-email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="nume@companie.ro" className={consultFieldCls} />
                    </div>
                  ) : (
                    <div>
                      <label htmlFor="cons-slot" className={consultLabelCls}>Interval preferat</label>
                      <div className="relative">
                        <select id="cons-slot" value={slot} onChange={(e) => setSlot(e.target.value)} className={consultFieldCls + " pr-9 appearance-none"}>
                          {CONSULT_SLOTS.map((s) => <option key={s} value={s}>{s}</option>)}
                        </select>
                        <Icon name="chevron-down" className="w-4 h-4 absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" strokeWidth={2} />
                      </div>
                    </div>
                  )}
                </div>
                <div>
                  <label htmlFor="cons-domain" className={consultLabelCls}>Domeniu / proces</label>
                  <div className="relative">
                    <select id="cons-domain" value={domain} onChange={(e) => setDomain(e.target.value)} className={consultFieldCls + " pr-9 appearance-none"}>
                      {CONSULT_DOMAINS.map((d) => <option key={d} value={d}>{d}</option>)}
                    </select>
                    <Icon name="chevron-down" className="w-4 h-4 absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" strokeWidth={2} />
                  </div>
                </div>
                <div>
                  <label htmlFor="cons-params" className={consultLabelCls}>Parametri <span className="text-muted-foreground/70 normal-case tracking-normal font-normal">(opțional)</span></label>
                  <input id="cons-params" type="text" value={params} onChange={(e) => setParams(e.target.value)} placeholder="ex. 12 bar · 180°C · 500 kg/h" className={consultFieldCls} />
                </div>
                <div>
                  <label htmlFor="cons-msg" className={consultLabelCls}>Descrie pe scurt aplicația <span className="text-muted-foreground/70 normal-case tracking-normal font-normal">(opțional)</span></label>
                  <textarea id="cons-msg" rows={2} value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Ce vrei să rezolvi, unde se folosește, eventuale constrângeri…" className={consultFieldCls + " resize-none"} />
                </div>
                <div>
                  <label className={consultLabelCls}>Atașament <span className="text-muted-foreground/70 normal-case tracking-normal font-normal">(opțional)</span></label>
                  <input ref={fileInputRef} type="file" onChange={(e) => validateFile(e.target.files && e.target.files[0] || null)} accept=".pdf,.docx,.xlsx,.dwg,.jpg,.jpeg,.png" className="hidden" aria-label="Adaugă fișier" />
                  {!file ? (
                    <div onClick={() => fileInputRef.current && fileInputRef.current.click()}
                      onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }} onDragLeave={() => setIsDragging(false)} onDrop={onDrop}
                      role="button" tabIndex={0}
                      className={`flex items-center gap-3 px-4 py-3 border-2 border-dashed rounded-sm cursor-pointer transition-colors ${isDragging ? 'border-accent bg-accent/5' : 'border-border bg-muted/30 hover:border-accent/60 hover:bg-muted/50'}`}>
                      <Icon name="paperclip" className="w-4 h-4 text-muted-foreground flex-shrink-0" strokeWidth={2} />
                      <div className="flex-grow min-w-0">
                        <div className="text-sm font-semibold text-foreground/80 leading-tight">Adaugă fișier</div>
                        <div className="text-xs text-muted-foreground mt-0.5">PDF, DOCX, XLSX, DWG, JPG, PNG · max {MAX_MB}MB</div>
                      </div>
                    </div>
                  ) : (
                    <div className="flex items-center gap-3 px-4 py-3 border border-border bg-muted/40 rounded-sm">
                      <Icon name="paperclip" className="w-4 h-4 text-accent flex-shrink-0" strokeWidth={2} />
                      <div className="flex-grow min-w-0">
                        <div className="text-sm font-semibold text-foreground truncate leading-tight">{file.name}</div>
                        <div className="text-xs text-muted-foreground mt-0.5">{fmtSize(file.size)}</div>
                      </div>
                      <button type="button" onClick={() => { setFile(null); setFileError(null); if (fileInputRef.current) fileInputRef.current.value = ''; }} className="p-1 text-muted-foreground hover:text-foreground transition-colors flex-shrink-0" aria-label="Elimină fișierul">
                        <Icon name="x" className="w-4 h-4" />
                      </button>
                    </div>
                  )}
                  {fileError && (
                    <div className="flex items-center gap-1.5 mt-2 text-xs text-destructive">
                      <Icon name="alert-circle" className="w-3.5 h-3.5" strokeWidth={2} />
                      {fileError}
                    </div>
                  )}
                </div>
                <button type="submit" disabled={submitting} className="w-full inline-flex items-center justify-center gap-2 bg-accent hover:bg-accent/90 disabled:opacity-60 text-accent-foreground px-6 py-3.5 rounded-sm font-semibold text-base transition-colors group">
                  {submitting ? (
                    <><span className="w-4 h-4 border-2 border-accent-foreground/30 border-t-accent-foreground rounded-full animate-spin" />Se trimite…</>
                  ) : (
                    <>Trimite cererea<Icon name="arrow-right" className="w-4 h-4 group-hover:translate-x-1 transition-transform" /></>
                  )}
                </button>
                <p className="text-xs text-muted-foreground leading-snug">Te contactăm în max 24h în zile lucrătoare · Datele tale rămân la noi · GDPR</p>
              </form>
              </div>
              <div className="md:col-span-2 flex flex-col">
                <h4 className="font-headings text-base font-bold text-primary leading-tight mb-4">De ce să vorbești cu un inginer</h4>
                <div className="bg-muted/40 border border-border rounded-sm p-5 space-y-4">
                  {[
                    { icon: 'check-circle', t: 'Gratuit, fără obligație', d: 'O discuție tehnică, nu un angajament comercial.' },
                    { icon: 'clock', t: 'Răspuns în 24h', d: 'Te contactăm în max 24h în zile lucrătoare.' },
                    { icon: 'gauge', t: 'Dimensionare corectă', d: 'Alegem și dimensionăm echipamentul pentru procesul tău.' },
                  ].map((b) => (
                    <div key={b.t} className="flex items-start gap-3">
                      <Icon name={b.icon} className="w-4 h-4 text-accent flex-shrink-0 mt-0.5" strokeWidth={2} />
                      <div>
                        <div className="text-sm font-semibold text-foreground leading-tight">{b.t}</div>
                        <div className="text-sm text-foreground/70 leading-snug mt-0.5">{b.d}</div>
                      </div>
                    </div>
                  ))}
                </div>
                <h4 className="font-headings text-base font-bold text-primary leading-tight mb-4 mt-6">Sau contactează-ne direct</h4>
                <div className="bg-muted/40 border border-border rounded-sm p-5 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 group-hover:text-accent transition-colors">+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 group-hover:text-accent transition-colors">+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 group-hover:text-accent transition-colors truncate">rea@romenergy.ro</div>
                    </div>
                  </a>
                  <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>
              </div>
            </div>
          )}
        </div>
      </ModalShell>
    );
  }

  Object.assign(window, { Eyebrow, GridBg, SectionHeader, CategoryCard, CategoryCardGrid, ModalShell, ContactModal, ConsultModal });
  // Global openers — any in-page CTA can call these; the Header mounts the modal
  // and listens for the event, so a button anywhere opens the right surface.
  window.openQuoteModal = () => window.dispatchEvent(new CustomEvent('rea:open-quote'));
  window.openConsultModal = () => window.dispatchEvent(new CustomEvent('rea:open-consult'));
})();
