// =====================================================
// PAGE — Espace opérateurs
// =====================================================

const OperateursPage = ({ navigate }) => {
  const catalogueHref = (typeof CONFIG !== "undefined" && CONFIG.PDF_CATALOGUE)
    ? CONFIG.PDF_CATALOGUE
    : "assets/catalogue-croisieres-2026.pdf";

  const exportCsv = () => {
    const headers = [
      "Escale", "Nom alternatif", "Type d'accueil", "Quai / mouillage",
      "Terminal", "Pilotage", "Remorqueurs", "Aeroport proche",
      "Segment", "Premier point a confirmer", "Fiabilite"
    ];
    const escapeCell = (value) => `"${String(value || "").replace(/"/g, '""')}"`;
    const rows = ESCALES.map(e => [
      e.nom,
      e.nomAlt,
      e.typeAccueil,
      e.quai,
      e.terminal,
      e.pilotage,
      e.remorqueurs,
      e.aeroport,
      e.segment,
      e.pointsAConfirmer && e.pointsAConfirmer[0],
      e.fiabilite
    ]);
    const csv = "\uFEFF" + [headers, ...rows].map(row => row.map(escapeCell).join(";")).join("\n");
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "comparatif-escales-croisieres-madagascar-2026.csv";
    document.body.appendChild(link);
    link.click();
    link.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  return (
    <main className="app-main">
      <section className="section">
        <div className="container container-wide">
          <div className="section-head">
            <span className="h-eyebrow">B2B · Compagnies, armateurs, tour-opérateurs, agences</span>
            <h1 className="h-section">Planifier une escale<br/><em>croisière à Madagascar</em></h1>
            <p className="lede">
              Madagascar propose plusieurs types d'escales&nbsp;: ports en eau profonde, ports
              commerciaux, mouillages tender et escales d'expédition. Les données techniques
              doivent être vérifiées auprès des autorités compétentes avant toute
              programmation opérationnelle.
            </p>
          </div>

          {/* Comparative table */}
          <div style={{ marginBottom: 56 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16, flexWrap: "wrap", gap: 12 }}>
              <h2 className="h-card" style={{ fontSize: 28 }}>Tableau comparatif des escales</h2>
              <div style={{ display: "flex", gap: 10 }}>
                <button className="btn btn-ghost btn-sm" onClick={exportCsv}><Icon name="download" size={13}/>Exporter (CSV)</button>
                <a className="btn btn-navy btn-sm" href={catalogueHref} download><Icon name="file" size={13}/>Télécharger le PDF</a>
              </div>
            </div>
            <ComparativeTable navigate={navigate}/>
            <p className="note" style={{ marginTop: 12 }}>
              <strong>Lecture&nbsp;:</strong> les cases « Non précisé dans le catalogue » et « À confirmer »
              indiquent qu'une validation auprès des autorités est nécessaire avant programmation.
            </p>
          </div>

          {/* Operator blocks */}
          <div className="op-grid">
            <div className="col" style={{ gap: 20 }}>
              <div className="op-block">
                <h3>Comment lire les fiches escales</h3>
                <p>Chaque fiche propose une double lecture B2C / B2B. Le bloc « Découvrir » présente les expériences pour les passagers&nbsp;; le bloc « Infos opérateurs » regroupe les données techniques d'aide à la décision.</p>
                <ul>
                  <li>Faisabilité opérationnelle&nbsp;: type d'accueil, quai/mouillage, profondeur</li>
                  <li>Valeur commerciale de l'escale&nbsp;: argument différenciant et clientèle cible</li>
                  <li>Contraintes &amp; points à confirmer auprès de l'APMF / capitainerie</li>
                </ul>
              </div>

              <div className="op-block">
                <h3>Coordination avec les autorités compétentes</h3>
                <p>La programmation d'une escale nécessite une coordination préalable avec&nbsp;:</p>
                <ul>
                  <li>L'Agence Portuaire, Maritime et Fluviale (APMF)</li>
                  <li>La capitainerie du port d'escale concerné</li>
                  <li>Les autorités locales et les services douaniers</li>
                  <li>Les agents maritimes mandatés sur place</li>
                </ul>
                <p className="note">Délai recommandé&nbsp;: contact 48 heures minimum avant escale ; davantage pour les escales exploratoires comme Antalaha.</p>
              </div>

              <div className="op-block">
                <h3>Contraintes météo &amp; saisonnalité</h3>
                <p>Saison cyclonique de décembre à mars sur l'ensemble de la côte malgache. Les fenêtres opérationnelles varient selon les façades&nbsp;:</p>
                <ul>
                  <li>Façade nord et ouest&nbsp;: saison sèche mai à octobre (idéale)</li>
                  <li>Façade est&nbsp;: meilleure fenêtre mai à septembre</li>
                  <li>Sud / Sud-Est&nbsp;: amplitude plus large grâce au climat austral</li>
                  <li>Nord-Est (Maroantsetra, Antalaha)&nbsp;: période sèche relative juillet à septembre</li>
                </ul>
              </div>
            </div>

            <div className="col" style={{ gap: 20 }}>
              <div className="op-block">
                <h3>Points à confirmer avant programmation</h3>
                <p>La majorité des données techniques du catalogue restent indicatives. Les points suivants sont systématiquement à valider auprès des autorités&nbsp;:</p>
                <ul>
                  <li>Tirant d'eau et amplitude de marée selon la période</li>
                  <li>Disponibilité du quai ou du poste de mouillage</li>
                  <li>Pilotage et mobilisation des remorqueurs</li>
                  <li>Procédures ISPS et flux passagers (shuttle)</li>
                  <li>Logistique terrestre des excursions longues (Tsingy, Masoala, Marojejy)</li>
                </ul>
              </div>

              <div className="op-block" style={{ background: "var(--c-navy)", borderColor: "var(--c-navy)", color: "#fff" }}>
                <h3 style={{ color: "#fff" }}>Ressources téléchargeables</h3>
                <p style={{ color: "rgba(255,255,255,.78)" }}>Documents officiels du Ministère du Tourisme et de l'Artisanat — Catalogue Croisières Madagascar 2026.</p>
                <div className="dl-list">
                  <a className="dl-row" href={catalogueHref} download style={{ background: "rgba(255,255,255,.06)", borderColor: "rgba(255,255,255,.12)" }}>
                    <div className="dl-ico" style={{ background: "rgba(232,90,31,.2)", color: "var(--c-terra)" }}>
                      <Icon name="file" size={18}/>
                    </div>
                    <div className="dl-meta">
                      <div className="dl-title" style={{ color: "#fff" }}>Catalogue Croisières Madagascar 2026</div>
                      <div className="dl-desc" style={{ color: "rgba(255,255,255,.6)" }}>PDF · Édition officielle MTA</div>
                    </div>
                    <Icon name="download" size={18} stroke={2}/>
                  </a>
                  <div className="dl-row is-disabled" aria-disabled="true" style={{ background: "rgba(255,255,255,.06)", borderColor: "rgba(255,255,255,.12)" }}>
                    <div className="dl-ico" style={{ background: "rgba(91,180,212,.2)", color: "var(--c-ocean)" }}>
                      <Icon name="briefcase" size={18}/>
                    </div>
                    <div className="dl-meta">
                      <div className="dl-title" style={{ color: "#fff" }}>Fiche synthèse B2B</div>
                      <div className="dl-desc" style={{ color: "rgba(255,255,255,.6)" }}>PDF · Données opérationnelles condensées</div>
                    </div>
                    <span className="dl-desc" style={{ color: "rgba(255,255,255,.55)" }}>À venir</span>
                  </div>
                  <div className="dl-row is-disabled" aria-disabled="true" style={{ background: "rgba(255,255,255,.06)", borderColor: "rgba(255,255,255,.12)" }}>
                    <div className="dl-ico" style={{ background: "rgba(127,181,57,.2)", color: "var(--c-green)" }}>
                      <Icon name="calendar" size={18}/>
                    </div>
                    <div className="dl-meta">
                      <div className="dl-title" style={{ color: "#fff" }}>Calendrier des escales</div>
                      <div className="dl-desc" style={{ color: "rgba(255,255,255,.6)" }}>Excel / CSV · à venir</div>
                    </div>
                    <span className="dl-desc" style={{ color: "rgba(255,255,255,.55)" }}>À venir</span>
                  </div>
                </div>
                <div style={{ marginTop: 12, display: "flex", gap: 10 }}>
                  <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={() => navigate("#/contact")}>
                    <Icon name="mail" size={13}/>Contacter le Ministère
                  </button>
                  <button className="btn btn-ghost btn-sm" style={{ flex: 1, color: "#fff", borderColor: "rgba(255,255,255,.2)" }} onClick={() => navigate("#/contact")}>
                    Mise en relation
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
};

// ==============================
// Comparative table — desktop + mobile cards
// ==============================
const ComparativeTable = ({ navigate }) => (
  <>
    {/* ── Vue tableau (desktop) ── */}
    <div className="table-wrap comp-table-desktop">
      <table className="t">
        <thead>
          <tr>
            <th style={{ minWidth: 160 }}>Escale</th>
            <th>Type d'accueil</th>
            <th>Quai / mouillage</th>
            <th>Terminal</th>
            <th>Pilotage</th>
            <th>Remorqueurs</th>
            <th>Aéroport proche</th>
            <th>Segment</th>
            <th>À confirmer</th>
            <th>Fiabilité</th>
          </tr>
        </thead>
        <tbody>
          {ESCALES.map(e => (
            <tr key={e.id} style={{ cursor: "pointer" }} onClick={() => navigate(`#/escale/${e.id}`)}>
              <td>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{ width: 24, height: 24, borderRadius: 50, background: e.couleur, color: "#fff", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, flexShrink: 0 }}>{e.num}</span>
                  <div>
                    <div style={{ fontWeight: 600, color: "var(--c-navy)" }}>{e.nom}</div>
                    <div style={{ fontSize: 11, color: "var(--c-mute)" }}>{e.nomAlt}</div>
                  </div>
                </div>
              </td>
              <td>{e.typeAccueil.split("·")[0].trim()}</td>
              <td style={{ maxWidth: 200 }}>{e.quai}</td>
              <td><CellStatus value={e.terminal}/></td>
              <td><CellStatus value={e.pilotage}/></td>
              <td><CellStatus value={e.remorqueurs}/></td>
              <td>{e.aeroport.split("·")[0].trim()}</td>
              <td style={{ maxWidth: 180 }}>{e.segment.split("·")[0].trim()}</td>
              <td style={{ maxWidth: 220, fontSize: 12, color: "var(--c-ink-soft)" }}>{e.pointsAConfirmer[0] || "—"}</td>
              <td><FiabilityBadge niveau={e.fiabilite} small/></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>

    {/* ── Vue cartes (mobile/tablette) ── */}
    <div className="comp-cards">
      {ESCALES.map(e => (
        <div className="comp-card" key={e.id} onClick={() => navigate(`#/escale/${e.id}`)}>
          <div className="cc-head">
            <span className="cc-dot" style={{ background: e.couleur }}>{e.num}</span>
            <div className="cc-title">
              <span className="cc-nom">{e.nom}</span>
              <span className="cc-alt">{e.nomAlt}</span>
            </div>
            <FiabilityBadge niveau={e.fiabilite} small/>
          </div>
          <div className="cc-grid">
            <CompRow label="Type d'accueil"  value={e.typeAccueil.split("·")[0].trim()}/>
            <CompRow label="Quai / mouillage" value={e.quai}/>
            <CompRow label="Terminal"         value={<CellStatus value={e.terminal}/>}/>
            <CompRow label="Pilotage"         value={<CellStatus value={e.pilotage}/>}/>
            <CompRow label="Remorqueurs"      value={<CellStatus value={e.remorqueurs}/>}/>
            <CompRow label="Aéroport proche"  value={e.aeroport.split("·")[0].trim()}/>
            <CompRow label="Segment"          value={e.segment.split("·")[0].trim()}/>
          </div>
          {e.pointsAConfirmer.length > 0 && (
            <div className="cc-confirm">
              <span className="cc-confirm-label">
                <Icon name="alert" size={11} stroke={2.2}/>
                {e.pointsAConfirmer.length} point{e.pointsAConfirmer.length > 1 ? "s" : ""} à confirmer
              </span>
              <span className="cc-confirm-first">{e.pointsAConfirmer[0]}</span>
            </div>
          )}
          <div className="cc-foot">
            <span className="note" style={{ fontSize: 11 }}>{e.facade}</span>
            <span className="btn btn-link btn-sm" style={{ padding: 0, fontSize: 12 }}>
              Fiche complète <Icon name="arrow-right" size={12}/>
            </span>
          </div>
        </div>
      ))}
    </div>
  </>
);

const CompRow = ({ label, value }) => (
  <div className="cc-row">
    <span className="cc-lbl">{label}</span>
    <span className="cc-val">{value}</span>
  </div>
);

const CellStatus = ({ value }) => {
  if (!value) return <span className="note">Non précisé</span>;
  const mood = window.statusMood(value);
  const color = mood === "ok" ? "#4F7826" : mood === "warn" ? "#B23F0E" : mood === "no" ? "var(--c-mute)" : "var(--c-navy)";
  return <span style={{ color, fontWeight: 600, fontSize: 12.5 }}>{value}</span>;
};

window.OperateursPage = OperateursPage;
