/* global React, SERVICES_DATA, SERVICES_STATS, POLE_ICONS */
const { useState: useState_s, useMemo: useMemo_s } = React;

function SpecialtyCard({ s, onBook }) {
  const isOpen = s.status === "open";
  const total = s.items.length;
  const openCount = s.items.filter(it => it.status === "open").length;
  const pct = total === 0
    ? (isOpen ? 100 : 0)
    : Math.round((openCount / total) * 100);
  const Icon = POLE_ICONS[s.pole] || window.IconHeart;
  const visible = s.items.slice(0, 4);
  const rest = Math.max(0, s.items.length - visible.length);

  return (
    <article className="specialty-card">
      <div className="head">
        <div>
          <div style={{display:"flex", alignItems:"center", gap:10, marginBottom: 8}}>
            <span style={{
              width: 32, height: 32, borderRadius: 8,
              background: "var(--chic-50)", color: "var(--chic-800)",
              display: "inline-flex", alignItems: "center", justifyContent: "center"
            }}>
              <Icon size={16} />
            </span>
          </div>
          <div className="name">{s.name}</div>
          <div className="pole">{s.pole}</div>
        </div>
        <StatusPill status={s.status} dense />
      </div>

      {total > 0 && (
        <div className="progress" title={`${openCount} sur ${total} actes disponibles`}>
          <div className="bar"><div className="bar-fill" style={{ width: pct + "%" }} /></div>
          <div className="ratio">{openCount}/{total}</div>
        </div>
      )}

      {visible.length > 0 && (
        <ul className="items">
          {visible.map((it, i) => <li key={i} className={it.status}>{it.name}</li>)}
        </ul>
      )}
      {rest > 0 && <div className="more">+ {rest} autres</div>}

      {isOpen && (
        <a className="cta" onClick={(e) => { e.preventDefault(); onBook && onBook(s); }} href="#/rdv">
          Prendre RDV en {s.name.split(" ")[0]}
          <IconArrowRight />
        </a>
      )}
      {!isOpen && (
        <a className="cta" href="#" style={{color:"var(--chic-400)"}} onClick={e=>e.preventDefault()}>
          M’alerter à l’ouverture
          <IconArrowRight />
        </a>
      )}
    </article>
  );
}

function ServicesPage({ tweaks, onBook }) {
  const [q, setQ]               = useState_s("");
  const [statusF, setStatusF]   = useState_s("all"); // all | open | soon
  const [poleF, setPoleF]       = useState_s("all"); // pole name or "all"

  const stats = SERVICES_STATS;
  const data  = SERVICES_DATA;

  const poles = useMemo_s(() => {
    const set = new Set(data.map(s => s.pole));
    return Array.from(set);
  }, []);

  const filtered = useMemo_s(() => {
    return data.filter(s => {
      if (statusF !== "all" && s.status !== statusF) return false;
      if (poleF !== "all" && s.pole !== poleF) return false;
      if (q.trim()) {
        const needle = q.trim().toLowerCase();
        const hay = (s.name + " " + s.pole + " " + s.items.map(i => i.name).join(" ")).toLowerCase();
        if (!hay.includes(needle)) return false;
      }
      return true;
    });
  }, [q, statusF, poleF]);

  return (
    <main>
      {/* Hero */}
      <section className="hero">
        <div className="hero-split">
          <div className="text">
            <div className="hero-eyebrow eyebrow">Ouverture progressive · depuis juin 2025 · mise à jour temps réel</div>
            <h1 className="h1">
              Services{" "}
              <span className="italic-accent">déjà disponibles</span>{" "}
              au CHIC
            </h1>
            <p className="lead">
              Au sommet du 4<sup>e</sup> niveau de la pyramide sanitaire nationale, le CHIC ouvre ses services
              de manière échelonnée, pour un démarrage sécurisé et maîtrisé. Suivez en temps réel l’état d’ouverture.
            </p>
            <div className="hero-actions">
              <a href="#/rdv" className="btn btn-primary btn-lg">
                Prendre rendez-vous <IconArrowRight size={14} />
              </a>
              <a href="#" className="btn btn-outline btn-lg" onClick={e=>e.preventDefault()}>
                <IconDownload size={14} /> Télécharger la plaquette
              </a>
            </div>
          </div>
          <div className="visual">
            <img src="assets/photos/aerial-day.jpg" alt="Le Centre Hospitalier International de Calavi" />
          </div>
        </div>

        {/* Stats strip */}
        <div className="hero-stats">
          <div className="cell">
            <Stat value="434" label="Lits & places (cible)" />
          </div>
          <div className="cell">
            <Stat value="8" label="Pôles médicaux" />
          </div>
          <div className="cell">
            <Stat value="18" label="Spécialités médicales et chirurgicales" />
          </div>
        </div>
      </section>

      {/* Crumbs */}
      <div className="container">
        <Crumbs trail={[
          { label: "Accueil", href: "#/" },
          { label: "Nos spécialités", href: "#/services" },
          { label: "Services disponibles" },
        ]} />
      </div>

      {/* Live tracker */}
      <section className="section tight" style={{paddingTop: 24}}>
        <div className="container">
          <FadeUp>
            <div className="tracker-summary">
              <div className="item"><b><Counter to={stats.openSpec} /></b> spécialités ouvertes <span style={{color:"var(--chic-300)"}}>sur {stats.totalSpec}</span></div>
              <div className="item"><b><Counter to={stats.openActs} /></b> actes &amp; examens disponibles <span style={{color:"var(--chic-300)"}}>sur {stats.totalActs}</span></div>
              <div className="item" style={{marginLeft:"auto", fontFamily:"var(--mono)", fontSize:12, color:"var(--chic-400)"}}>Dernière mise à jour · {new Date().toLocaleDateString("fr-FR", {day:"numeric", month:"long", year:"numeric"})}</div>
            </div>
          </FadeUp>
        </div>

        <div className="tracker-toolbar" style={{ marginTop: 0 }}>
          <div className="container">
            <div className="tracker-toolbar-inner">
              <label className="tracker-search">
                <IconSearch size={18} />
                <input
                  type="search"
                  placeholder="Rechercher une spécialité, un acte, un examen…"
                  value={q}
                  onChange={e => setQ(e.target.value)}
                  aria-label="Rechercher"
                />
              </label>
              <div className="chip-row">
                <button className={`chip ${statusF === "all"  ? "active" : ""}`} onClick={()=>setStatusF("all")}>Tous <span className="ct">{stats.totalSpec}</span></button>
                <button className={`chip ${statusF === "open" ? "active" : ""}`} onClick={()=>setStatusF("open")}>
                  <span style={{width:6,height:6,borderRadius:"50%", background:"var(--open)", display:"inline-block"}} />
                  Disponibles <span className="ct">{stats.openSpec}</span>
                </button>
                <button className={`chip ${statusF === "soon" ? "active" : ""}`} onClick={()=>setStatusF("soon")}>
                  <span style={{width:6,height:6,borderRadius:"50%", background:"var(--soon)", display:"inline-block"}} />
                  Bientôt <span className="ct">{stats.soonSpec}</span>
                </button>
              </div>
            </div>
            <div className="pole-filter-row">
              <button className={`chip ${poleF === "all" ? "active" : ""}`} onClick={()=>setPoleF("all")}>Tous les pôles</button>
              {poles.map(p => (
                <button key={p} className={`chip ${poleF === p ? "active" : ""}`} onClick={()=>setPoleF(p)}>{p}</button>
              ))}
            </div>
          </div>
        </div>

        <div className="container" style={{ paddingTop: 36 }}>
          {filtered.length === 0 ? (
            <div className="empty-state">
              <IconSearch size={28} />
              <p style={{marginTop: 14}}>Aucun service ne correspond à votre recherche.</p>
              <button className="btn btn-ghost" onClick={() => { setQ(""); setStatusF("all"); setPoleF("all"); }}>Réinitialiser les filtres</button>
            </div>
          ) : (
            <div className={`tracker-grid ${tweaks.density === "compact" ? "compact" : ""}`}>
              {filtered.map((s, i) => (
                <SpecialtyCard key={s.name} s={s} onBook={onBook} />
              ))}
            </div>
          )}
        </div>
      </section>

      {/* CTA band */}
      <section className="section tight">
        <div className="container">
          <div className="cta-band">
            <div>
              <div className="eyebrow" style={{marginBottom:12}}>Besoin d’aide pour vous orienter ?</div>
              <h3 className="h3">Notre standard vous oriente vers le bon service.</h3>
              <p className="lead" style={{marginTop:12, fontSize:15}}>
                Du lundi au vendredi, 8h–17h. Le CHIC fonctionne exclusivement sur rendez-vous.
                Paiement par Mobile Money à la prise de RDV.
              </p>
            </div>
            <div className="right">
              <a className="btn btn-outline btn-lg" href="tel:+22901214000100">
                <IconPhone size={14} /> +229 01 21 400 100
              </a>
              <a className="btn btn-primary btn-lg" href="#/rdv">
                Prendre rendez-vous <IconArrowRight size={14} />
              </a>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

window.ServicesPage = ServicesPage;
