import { useState, useMemo } from "react";
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, AreaChart, Area, Legend, CartesianGrid } from "recharts";

/* FRANCIRIS ANALYTICS — LE TABLEAU DE BORD DU CONCOURS */

const editions = [
  { year: 2000, lieu: "Jardins de Brocéliande", type: "national",
    entries: 14, hybrideurs: 6, pays: 1,
    jury_president: "Paolo Gambassini (IT)",
    podium: [
      { rank: 1, cultivar: "Samsara", hybrideur: "Lawrence Ransom", pays: "France", special: "La plus originale" },
      { rank: 2, cultivar: "Mer du Sud", hybrideur: "Cayeux", pays: "France", special: "La plus parfumée" },
      { rank: 3, cultivar: "Damoiselle", hybrideur: "Lawrence Ransom", pays: "France" },
      { rank: 4, cultivar: "Claude Louis Gayrard", hybrideur: "Ransom", pays: "France" },
      { rank: 5, cultivar: "Massalia", hybrideur: "Anfosso", pays: "France" },
    ],
    prix_public: "Provençal (Cayeux)",
    prix_parfum: "Mer du Sud (Cayeux)",
  },
  { year: 2005, lieu: "TECOMAH, Jouy-en-Josas", type: "international",
    entries: 121, hybrideurs: 24, pays: 7,
    jury_president: "E. Roy Epperson (US)",
    podium: [
      { rank: 1, cultivar: "Bye Bye Blues", hybrideur: "George Sutton", pays: "USA" },
      { rank: 2, cultivar: "Chariots of Fire", hybrideur: "Aitken", pays: "USA" },
      { rank: 3, cultivar: "Got Milk", hybrideur: "Aitken", pays: "USA" },
      { rank: 4, cultivar: "Finnigan\u2019s Finagling Factor", hybrideur: "Stetson", pays: "USA" },
      { rank: 5, cultivar: "Gwennaden", hybrideur: "Madoré", pays: "France" },
      { rank: 6, cultivar: "Diabolique", hybrideur: "Schreiner", pays: "USA" },
    ],
    prix_public: "World Premier (Schneider)",
    prix_parfum: "Pretty Edgy (Blyth, AU)",
    prix_francais: "Gwennaden (Madoré)",
  },
  { year: 2007, lieu: "TECOMAH, Jouy-en-Josas", type: "international",
    entries: 34, hybrideurs: null, pays: null,
    jury_president: "Stephanie Boot (NZ)",
    note: "Floraison avancée de 3 semaines",
    podium: [
      { rank: 1, cultivar: "Solovinaya Noch\u2019", hybrideur: "Nina Miroshnichenko", pays: "Ukraine" },
      { rank: 2, cultivar: "Mamy Framboise", hybrideur: "Virginie Fur", pays: "France" },
      { rank: 3, cultivar: "Italian Ice", hybrideur: "A.D. Cadd", pays: "USA" },
    ],
    prix_public: "Toréro (Cayeux)",
    prix_parfum: "Arcobaleno (Mostosi, IT)",
    prix_francais: "Mamy Framboise (Fur)",
  },
  { year: 2011, lieu: "TECOMAH, Jouy-en-Josas", type: "international",
    entries: null, hybrideurs: null, pays: null,
    jury_president: "Valeria Rosselli (IT)",
    podium: [
      { rank: 1, cultivar: "Aleutian Islands", hybrideur: "Michael Sutton", pays: "USA" },
      { rank: 2, cultivar: "Échirolles", hybrideur: "Laporte", pays: "France" },
      { rank: 3, cultivar: "Danube du Barry", hybrideur: "Vasquez-Poupin", pays: "France" },
    ],
    prix_public: "Grenade (Cayeux)",
    prix_parfum: "semis 060402 (Jacob)",
  },
  { year: 2015, lieu: "Parc Floral de Paris", type: "international",
    entries: 113, hybrideurs: 31, pays: null,
    jury_president: "Kathy Chilton (US)",
    podium: [
      { rank: 1, cultivar: "Barbe Noire", hybrideur: "Richard Cayeux", pays: "France" },
      { rank: 2, cultivar: "Cielo Alto", hybrideur: "Angelo Garanzini", pays: "Italie" },
      { rank: 3, cultivar: "Clotho\u2019s Web", hybrideur: "Anton Mego", pays: "Slovaquie" },
      { rank: 4, cultivar: "Clignotant", hybrideur: "Stéphane Boivin", pays: "France" },
      { rank: 5, cultivar: "Nuage de Lait / Fruit de la Passion", hybrideur: "Stéphane Boivin", pays: "France" },
      { rank: 7, cultivar: "Villa Erba", hybrideur: "Richard Cayeux", pays: "France" },
      { rank: 8, cultivar: "Guardian\u2019s Fire (sdlg)", hybrideur: "Anton Mego", pays: "Slovaquie" },
      { rank: 9, cultivar: "Fall Symphony", hybrideur: "Lorena Montanari", pays: "Italie" },
      { rank: 10, cultivar: "Braises Incandescentes", hybrideur: "Alain Chapelle", pays: "France" },
    ],
    prix_public: "Barbe Noire (Cayeux)",
    prix_parfum: "Cielo Alto (Garanzini)",
    prix_francais: "Richard Cayeux",
  },
  { year: 2017, lieu: "Parc Floral de Paris", type: "international",
    entries: 110, hybrideurs: 35, pays: null,
    jury_president: "Hooker Nichols (US)",
    podium: [
      { rank: 1, cultivar: "Chachar", hybrideur: "Zdeněk Seidl", pays: "Rép. tchèque" },
      { rank: 2, cultivar: "High Desert", hybrideur: "Keith Keppel", pays: "USA" },
      { rank: 3, cultivar: "Midnight Velvet", hybrideur: "Tom Johnson", pays: "USA" },
      { rank: 3, cultivar: "semis 06-2155-2", hybrideur: "Anton Mego", pays: "Slovaquie" },
      { rank: 5, cultivar: "Blackbird Tears", hybrideur: "Steve Poole", pays: "USA" },
      { rank: 6, cultivar: "Cigarillo", hybrideur: "Richard Cayeux", pays: "France" },
    ],
    prix_public: "Ogar (Seidl)",
    prix_gladys: "Cigarillo (Cayeux)",
    prix_ransom: "Blackbird Tears (Poole)",
  },
  { year: 2019, lieu: "Parc Floral de Paris", type: "international",
    entries: 120, hybrideurs: 35, pays: null,
    jury_president: "Andy Rivarola (US)",
    podium: [
      { rank: 1, cultivar: "My Red Drums", hybrideur: "Daniel Balland", pays: "France" },
      { rank: 2, cultivar: "Marry The Night", hybrideur: "Tom Johnson", pays: "USA" },
      { rank: 3, cultivar: "Beauté de Sologne (sdlg)", hybrideur: "Nicolas Bourdillon", pays: "France" },
      { rank: 4, cultivar: "Church Lady", hybrideur: "Burseen", pays: "USA" },
      { rank: 5, cultivar: "Locomotion", hybrideur: "Tom Johnson", pays: "USA" },
      { rank: 7, cultivar: "Mixed Signals", hybrideur: "Keith Keppel", pays: "USA" },
    ],
    prix_public: "Locomotion (Johnson)",
    prix_gladys: "My Red Drums (Balland)",
    prix_ransom: "Locomotion (Johnson)",
  },
  { year: 2022, lieu: "Parc Floral de Paris", type: "international",
    entries: null, hybrideurs: null, pays: null,
    jury_president: "Richard Cayeux (FR)",
    note: "Jury restreint post-COVID",
    podium: [
      { rank: 1, cultivar: "Nad Oblaky", hybrideur: "Zdeněk Seidl", pays: "Rép. tchèque" },
      { rank: 2, cultivar: "Les Avenières (sdlg)", hybrideur: "Stéphane Boivin", pays: "France" },
      { rank: 3, cultivar: "Sylvain Ruaud", hybrideur: "Daniel Balland", pays: "France" },
      { rank: 4, cultivar: "Secret Land", hybrideur: "Robert Piatek", pays: "Pologne" },
      { rank: 5, cultivar: "Santa Cruz Surf", hybrideur: "Joe Ghio", pays: "USA" },
      { rank: 6, cultivar: "Parfum Parisien (sdlg)", hybrideur: "Lorena Montanari", pays: "Italie" },
    ],
    prix_public: "Les Avenières (Boivin)",
    prix_gladys: "Les Avenières (Boivin)",
    prix_parfum: "Parfum Parisien (Montanari)",
    prix_ransom: "Maggese (Bianco, IT)",
  },
  { year: 2024, lieu: "Parc Floral de Paris", type: "international",
    entries: null, hybrideurs: null, pays: null,
    jury_president: "Sofia Cavini (IT)",
    podium: [
      { rank: 1, cultivar: "Hatshepsout", hybrideur: "Richard Cayeux", pays: "France" },
      { rank: 2, cultivar: "Behind The Rainbow", hybrideur: "Etienne Nouwen", pays: "Belgique" },
      { rank: 3, cultivar: "Prince Timeo", hybrideur: "Sébastien Cancade", pays: "France" },
      { rank: 4, cultivar: "Ignite The Light", hybrideur: "Tom Johnson", pays: "USA" },
      { rank: 5, cultivar: "Léon C\u2019est Moi", hybrideur: "Lorena Montanari", pays: "Italie" },
      { rank: 7, cultivar: "Zone 51", hybrideur: "Bénédicte Habert", pays: "France" },
    ],
    prix_public: "In Rosa Per Caso (V. Negri, IT)",
    prix_gladys: "Hatshepsout (Cayeux)",
    prix_parfum: "Rose de Porcelaine (Habert)",
  },
];

const florence = [
  { year: 2000, cultivar: "Diabolique", hybrideur: "Schreiner\u2019s", pays: "USA" },
  { year: 2001, cultivar: "H.C. Stetson", hybrideur: "R.E. Stetson II", pays: "USA" },
  { year: 2002, cultivar: "Dude Ranch", hybrideur: "Paul Black", pays: "USA" },
  { year: 2003, cultivar: "Pay The Price", hybrideur: "Graeme Grosvenor", pays: "Australie" },
  { year: 2004, cultivar: "Frosted Fantasy", hybrideur: "Anna & David Cadd", pays: "USA" },
  { year: 2005, cultivar: "Paul Black", hybrideur: "Thomas Johnson", pays: "USA" },
  { year: 2006, cultivar: "Recondita Armonia", hybrideur: "Mauro Bertuzzi", pays: "Italie" },
  { year: 2007, cultivar: "Aurélie", hybrideur: "Richard Cayeux", pays: "France" },
  { year: 2008, cultivar: "Morning Sunrise", hybrideur: "Thomas Johnson", pays: "USA" },
  { year: 2009, cultivar: "Ravissant", hybrideur: "Richard Cayeux", pays: "France" },
  { year: 2010, cultivar: "Alé Viola", hybrideur: "Stefano Gigli", pays: "Italie" },
  { year: 2011, cultivar: "Silk Road", hybrideur: "Keith Keppel", pays: "USA" },
  { year: 2012, cultivar: "Cheyenne My Dog", hybrideur: "Roberto Marucchi", pays: "Italie" },
  { year: 2013, cultivar: "Vento Di Maggio", hybrideur: "Augusto Bianco", pays: "Italie" },
  { year: 2014, cultivar: "Drifting", hybrideur: "Schreiner\u2019s", pays: "USA" },
  { year: 2017, cultivar: "Spirit Rider", hybrideur: "Schreiner\u2019s", pays: "USA" },
  { year: 2018, cultivar: "Anima Cara", hybrideur: "Angelo Garanzini", pays: "Italie" },
  { year: 2019, cultivar: "Chachar", hybrideur: "Zdeněk Seidl", pays: "Rép. tchèque" },
  { year: 2020, cultivar: "Dalí", hybrideur: "Augusto Bianco", pays: "Italie" },
  { year: 2021, cultivar: "Belle Fille", hybrideur: "Marky Smith", pays: "USA" },
  { year: 2022, cultivar: "Matka Theresa", hybrideur: "Robert Piatek", pays: "Pologne" },
  { year: 2023, cultivar: "Azzurro Cielo", hybrideur: "Angelo Garanzini", pays: "Italie" },
  { year: 2024, cultivar: "Me Pizzica", hybrideur: "Augusto Bianco", pays: "Italie" },
];

const aisAwards = [
  { cultivar: "Bye Bye Blues", hybrideur: "G. Sutton", pays: "USA", hm: 1999, am: 2002, other: null },
  { cultivar: "High Desert", hybrideur: "K. Keppel", pays: "USA", hm: 2017, am: 2019, other: null },
  { cultivar: "Locomotion", hybrideur: "T. Johnson", pays: "USA", hm: 2019, am: null, other: null },
  { cultivar: "Marry The Night", hybrideur: "T. Johnson", pays: "USA", hm: 2019, am: 2021, other: "Wister 2025" },
  { cultivar: "Santa Cruz Surf", hybrideur: "J. Ghio", pays: "USA", hm: 2021, am: null, other: null },
  { cultivar: "Barbe Noire", hybrideur: "R. Cayeux", pays: "France", hm: null, am: null, other: null },
  { cultivar: "Chachar", hybrideur: "Z. Seidl", pays: "Rép. tchèque", hm: null, am: null, other: "Fiorino d\u2019Oro 2019" },
  { cultivar: "My Red Drums", hybrideur: "D. Balland", pays: "France", hm: null, am: null, other: null },
  { cultivar: "Nad Oblaky", hybrideur: "Z. Seidl", pays: "Rép. tchèque", hm: null, am: null, other: null },
  { cultivar: "Hatshepsout", hybrideur: "R. Cayeux", pays: "France", hm: null, am: null, other: null },
  { cultivar: "Cielo Alto", hybrideur: "A. Garanzini", pays: "Italie", hm: null, am: null, other: null },
  { cultivar: "Behind The Rainbow", hybrideur: "E. Nouwen", pays: "Belgique", hm: null, am: null, other: null },
];

const GOLD = "#8B6914";
const BLUE = "#2C3E6B";
const COUNTRY_COLORS = {
  "France": "#2C3E6B", "USA": "#c0392b", "Italie": "#27ae60", "Ukraine": "#f1c40f",
  "Rép. tchèque": "#8e44ad", "Slovaquie": "#e67e22", "Pologne": "#e74c3c",
  "Belgique": "#1abc9c", "Australie": "#2ecc71",
};

function computeGeoData() {
  return editions.filter(e => e.type === "international").map(ed => {
    const counts = { year: ed.year, France: 0, USA: 0, "Europe (hors FR)": 0 };
    ed.podium.forEach(p => {
      if (p.pays === "France") counts["France"]++;
      else if (p.pays === "USA") counts["USA"]++;
      else counts["Europe (hors FR)"]++;
    });
    return counts;
  });
}

function computeHybrideurStats() {
  const stats = {};
  editions.forEach(ed => {
    ed.podium.forEach(p => {
      const key = p.hybrideur;
      if (!stats[key]) stats[key] = { nom: key, pays: p.pays, gp: 0, podiums: 0, top5: 0, total: 0, years: [] };
      stats[key].total++;
      if (p.rank === 1) stats[key].gp++;
      if (p.rank <= 3) stats[key].podiums++;
      if (p.rank <= 5) stats[key].top5++;
      if (!stats[key].years.includes(ed.year)) stats[key].years.push(ed.year);
    });
  });
  return Object.values(stats).sort((a,b) => b.podiums - a.podiums || b.gp - a.gp);
}

function computeCountryWins() {
  const wins = {};
  editions.forEach(ed => {
    const w = ed.podium.find(p => p.rank === 1);
    if (w) { wins[w.pays] = (wins[w.pays] || 0) + 1; }
  });
  return Object.entries(wins).map(([pays, count]) => ({ pays, count })).sort((a,b) => b.count - a.count);
}

function computeJuryVsPublic() {
  return editions.filter(e => e.prix_public).map(ed => {
    const winner = ed.podium[0];
    const pubText = ed.prix_public || "";
    const pubCultivar = pubText.split(" (")[0];
    const match = winner && pubCultivar.toLowerCase().includes(winner.cultivar.toLowerCase().substring(0,6));
    return { year: ed.year, jury: winner?.cultivar || "?", public_choice: pubCultivar, match };
  });
}

const NavSelect = ({ value, onChange, options }) => (
  <div style={{ background: "#FEF6CE", borderBottom: "2px solid " + GOLD, padding: "0.7rem 1.2rem", position: "sticky", top: 0, zIndex: 100, boxShadow: "0 2px 10px rgba(139,105,20,0.15)" }}>
    <div style={{ maxWidth: 960, margin: "0 auto", display: "flex", alignItems: "center", gap: "0.8rem" }}>
      <span style={{ fontFamily: "'DM Sans',sans-serif", fontSize: "0.78rem", fontWeight: 800, letterSpacing: "0.15em", textTransform: "uppercase", color: "#000", whiteSpace: "nowrap" }}>Vue</span>
      <select value={value} onChange={e => onChange(e.target.value)} style={{
        flex: 1, appearance: "none", WebkitAppearance: "none", background: "#fff",
        border: "1.5px solid rgba(0,0,0,0.35)", borderRadius: 4,
        padding: "0.55rem 2.5rem 0.55rem 0.85rem", fontFamily: "'DM Sans',sans-serif",
        fontSize: "0.92rem", fontWeight: 700, color: "#000", cursor: "pointer",
        backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='9' viewBox='0 0 14 9'%3E%3Cpath d='M1 1l6 6 6-6' stroke='%23000000' stroke-width='2' fill='none' stroke-linecap='round'/%3E%3C/svg%3E\")",
        backgroundRepeat: "no-repeat", backgroundPosition: "right 0.9rem center",
      }}>
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
    </div>
  </div>
);

const StatCard = ({ num, label }) => (
  <div style={{ background: "#F7F5F0", border: "1px solid #E8E2D8", borderRadius: 6, padding: "1rem 0.8rem", textAlign: "center" }}>
    <span style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: "2rem", fontWeight: 700, color: GOLD, lineHeight: 1, display: "block" }}>{num}</span>
    <span style={{ fontSize: "0.72rem", fontWeight: 700, color: "#6B6560", textTransform: "uppercase", letterSpacing: "0.08em", display: "block", marginTop: "0.3rem", lineHeight: 1.3 }}>{label}</span>
  </div>
);

const Var = ({ children }) => <em style={{ color: GOLD, fontWeight: 600 }}>{children}</em>;

const SectionTitle = ({ children, sub }) => (
  <div style={{ marginBottom: "1.8rem" }}>
    <h2 style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: "1.7rem", fontWeight: 700, color: "#000", lineHeight: 1.25, marginBottom: "0.4rem" }}>{children}</h2>
    {sub && <p style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: "1.05rem", fontStyle: "italic", color: "#6B6560", paddingBottom: "1rem", borderBottom: "1px solid #E8E2D8" }}>{sub}</p>}
  </div>
);

const H3 = ({ children }) => (
  <h3 style={{ fontFamily: "'DM Sans',sans-serif", fontSize: "1.05rem", fontWeight: 800, color: "#000", margin: "2rem 0 0.8rem", paddingBottom: "0.3rem", borderBottom: "1px solid #E8E2D8" }}>{children}</h3>
);

const InfoBox = ({ color, title, children }) => (
  <div style={{ background: color === "gold" ? "rgba(139,105,20,0.04)" : color === "blue" ? "rgba(44,62,107,0.04)" : "rgba(123,63,27,0.04)", border: "1px solid #E8E2D8", borderLeft: "4px solid " + (color === "gold" ? GOLD : color === "blue" ? BLUE : "#7B3F1B"), borderRadius: "0 8px 8px 0", padding: "1.2rem 1.4rem", margin: "2rem 0" }}>
    <h4 style={{ fontSize: "0.82rem", fontWeight: 800, color: "#000", letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: "0.5rem" }}>{title}</h4>
    <p style={{ fontSize: "0.9rem", lineHeight: 1.7 }}>{children}</p>
  </div>
);

const Table = ({ headers, rows, goldFirst }) => (
  <div style={{ overflowX: "auto", margin: "1.5rem 0", borderRadius: 6, border: "1px solid #E8E2D8", boxShadow: "0 1px 4px rgba(44,62,107,0.07)" }}>
    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.85rem" }}>
      <thead><tr style={{ background: "linear-gradient(135deg, " + BLUE + ", #5B6A8A)" }}>
        {headers.map((h,i) => <th key={i} style={{ fontFamily: "'DM Sans',sans-serif", fontWeight: 700, fontSize: "0.82rem", letterSpacing: "0.05em", padding: "0.7rem 0.9rem", textAlign: "left", color: "#fff" }}>{h}</th>)}
      </tr></thead>
      <tbody>{rows.map((row,ri) => (
        <tr key={ri} style={{ background: goldFirst && ri === 0 ? "rgba(139,105,20,0.08)" : ri % 2 === 1 ? "#F7F5F0" : "transparent" }}>
          {row.map((cell,ci) => <td key={ci} style={{ padding: "0.6rem 0.9rem", borderBottom: "1px solid #E8E2D8", verticalAlign: "top", lineHeight: 1.52 }}>{cell}</td>)}
        </tr>
      ))}</tbody>
    </table>
  </div>
);

const CustomTooltip = ({ active, payload, label }) => {
  if (!active || !payload?.length) return null;
  return (
    <div style={{ background: "#fff", border: "1px solid #E8E2D8", borderRadius: 6, padding: "0.6rem 0.8rem", fontSize: "0.8rem", boxShadow: "0 2px 8px rgba(0,0,0,0.1)" }}>
      <div style={{ fontWeight: 700, marginBottom: 4 }}>{label}</div>
      {payload.map((p,i) => <div key={i} style={{ color: p.color }}>{p.name}: {p.value}</div>)}
    </div>
  );
};

const CFlag = ({ pays }) => <span style={{ color: COUNTRY_COLORS[pays] || "#333", fontWeight: 600 }}>{pays}</span>;

// ═══ VUE D’ENSEMBLE ═══
const ViewOverview = () => {
  const countryWins = computeCountryWins();
  return (
    <div>
      <SectionTitle sub="10 éditions officielles · 2000–2024 · un quart de siècle d’hybridation jugée">{"Vue d\u2019ensemble"}</SectionTitle>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(130px, 1fr))", gap: "0.7rem", marginBottom: "2rem" }}>
        <StatCard num="10" label="éditions officielles" />
        <StatCard num="25" label="ans d’existence" />
        <StatCard num="3" label="lieux successifs" />
        <StatCard num="~120" label={"variétés / édition"} />
        <StatCard num="6" label="pays vainqueurs" />
      </div>
      <H3>Grand Prix Philippe de Vilmorin — tous les lauréats</H3>
      <Table headers={["Année", "Cultivar", "Hybrideur", "Pays"]} goldFirst={false}
        rows={editions.map(e => {
          const w = e.podium[0];
          return [<strong>{e.year}</strong>, <Var>{w?.cultivar}</Var>, w?.hybrideur, <CFlag pays={w?.pays} />];
        })} />
      <H3>Victoires par pays</H3>
      <div style={{ height: 280 }}>
        <ResponsiveContainer>
          <PieChart>
            <Pie data={countryWins} dataKey="count" nameKey="pays" cx="50%" cy="50%" outerRadius={100} label={({ pays, count }) => pays + " (" + count + ")"} labelLine={{ strokeWidth: 1 }} style={{ fontSize: "0.75rem" }}>
              {countryWins.map((d,i) => <Cell key={i} fill={COUNTRY_COLORS[d.pays] || "#999"} />)}
            </Pie>
            <Tooltip />
          </PieChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
};

// ═══ PALMARÈS ═══
const ViewPalmares = () => {
  const [selected, setSelected] = useState(editions[editions.length-1].year);
  const ed = editions.find(e => e.year === selected);
  const rankLabel = r => r === 1 ? "\ud83c\udfc6 1er" : r === 2 ? "\ud83e\udd48 2e" : r === 3 ? "\ud83e\udd49 3e" : r + "e";
  return (
    <div>
      <SectionTitle sub={"Sélectionnez une édition pour voir le classement complet"}>{"Palmarès complet"}</SectionTitle>
      <div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap", marginBottom: "1.5rem" }}>
        {editions.map(e => (
          <button key={e.year} onClick={() => setSelected(e.year)} style={{
            fontFamily: "'DM Sans',sans-serif", fontWeight: e.year === selected ? 800 : 600,
            fontSize: "0.85rem", padding: "0.4rem 0.9rem", borderRadius: 4, cursor: "pointer",
            border: e.year === selected ? "2px solid " + GOLD : "1.5px solid #E8E2D8",
            background: e.year === selected ? "rgba(139,105,20,0.08)" : "#fff",
            color: e.year === selected ? GOLD : "#333",
          }}>{e.year}</button>
        ))}
      </div>
      {ed && <>
        <div style={{ background: "#F7F5F0", border: "1px solid #E8E2D8", borderRadius: 8, padding: "1rem 1.2rem", marginBottom: "1.5rem", fontSize: "0.88rem" }}>
          <strong>{ed.lieu}</strong> {" \u2014 Président du jury : "}{ed.jury_president}
          {ed.entries && <span>{" \u00b7 "}{ed.entries}{" variétés"}</span>}
          {ed.hybrideurs && <span>{" \u00b7 "}{ed.hybrideurs}{" hybrideurs"}</span>}
          {ed.note && <div style={{ marginTop: 4, color: "#7B3F1B", fontStyle: "italic" }}>{ed.note}</div>}
        </div>
        <Table headers={["Rang", "Cultivar", "Hybrideur", "Pays"]} goldFirst={true}
          rows={ed.podium.map(p => [
            <strong style={{ color: p.rank <= 3 ? GOLD : "#333" }}>{rankLabel(p.rank)}</strong>,
            <Var>{p.cultivar}</Var>, p.hybrideur, <CFlag pays={p.pays} />
          ])} />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.7rem", marginTop: "1.2rem" }}>
          {[
            ed.prix_public && ["Prix du Public", ed.prix_public],
            ed.prix_parfum && ["Meilleur parfum", ed.prix_parfum],
            ed.prix_gladys && ["Prix Gladys Clarke", ed.prix_gladys],
            ed.prix_ransom && ["Prix Lawrence Ransom", ed.prix_ransom],
            ed.prix_francais && ["Meilleur français", ed.prix_francais],
          ].filter(Boolean).map(([lbl, val], i) => (
            <div key={i} style={{ background: "#F7F5F0", borderRadius: 6, padding: "0.8rem", border: "1px solid #E8E2D8" }}>
              <div style={{ fontSize: "0.7rem", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "#6B6560", marginBottom: 4 }}>{lbl}</div>
              <div style={{ fontSize: "0.9rem", fontWeight: 600 }}>{val}</div>
            </div>
          ))}
        </div>
      </>}
    </div>
  );
};

// ═══ GÉOPOLITIQUE ═══
const ViewGeo = () => {
  const regionData = useMemo(computeGeoData, []);
  return (
    <div>
      <SectionTitle sub={"Du monopole américain 2005 à la diversité européenne 2020"}>{"Basculement géopolitique"}</SectionTitle>
      <H3>{"Présence au classement par bloc géographique"}</H3>
      <div style={{ height: 300 }}>
        <ResponsiveContainer>
          <AreaChart data={regionData}>
            <CartesianGrid strokeDasharray="3 3" stroke="#E8E2D8" />
            <XAxis dataKey="year" tick={{ fontSize: 12 }} />
            <YAxis tick={{ fontSize: 12 }} />
            <Tooltip content={<CustomTooltip />} />
            <Legend />
            <Area type="monotone" dataKey="France" stackId="1" fill={BLUE} stroke={BLUE} fillOpacity={0.7} />
            <Area type="monotone" dataKey="USA" stackId="1" fill="#c0392b" stroke="#c0392b" fillOpacity={0.7} />
            <Area type="monotone" dataKey="Europe (hors FR)" stackId="1" fill="#8e44ad" stroke="#8e44ad" fillOpacity={0.7} />
          </AreaChart>
        </ResponsiveContainer>
      </div>
      <InfoBox color="gold" title="Lecture du graphique">
        <strong>2005</strong> : top 4 intégralement américain. <strong>2007</strong> : première victoire non-américaine (Ukraine). <strong>2015</strong> : tournant français historique (6 iris FR dans le top 10). <strong>2017–2022</strong> : l’Europe centrale (Seidl, Mego, Piatek) s’impose. <strong>2024</strong> : 5 pays représentés dans le top 7.
      </InfoBox>
    </div>
  );
};

// ═══ HYBRIDEURS ═══
const ViewHybrideurs = () => {
  const stats = useMemo(computeHybrideurStats, []);
  return (
    <div>
      <SectionTitle sub={"Classement cumulé sur les 10 éditions"}>{"Palmarès par hybrideur"}</SectionTitle>
      <Table headers={["Hybrideur", "Pays", "GP", "Podiums", "Top 5", "Total", "Éditions"]}
        rows={stats.slice(0,20).map(s => [
          <strong>{s.nom}</strong>, <CFlag pays={s.pays} />,
          s.gp > 0 ? <span style={{ color: GOLD, fontWeight: 700 }}>{s.gp}</span> : "\u2014",
          s.podiums, s.top5, s.total, s.years.join(", ")
        ])} goldFirst={false} />
      <H3>{"Podiums par hybrideur (top 10)"}</H3>
      <div style={{ height: 320 }}>
        <ResponsiveContainer>
          <BarChart data={stats.slice(0,10)} layout="vertical" margin={{ left: 120 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="#E8E2D8" />
            <XAxis type="number" tick={{ fontSize: 12 }} />
            <YAxis type="category" dataKey="nom" tick={{ fontSize: 11, fontWeight: 600 }} width={115} />
            <Tooltip content={<CustomTooltip />} />
            <Bar dataKey="gp" name="Grand Prix" fill={GOLD} stackId="a" />
            <Bar dataKey="podiums" name="Podiums" fill={BLUE} stackId="a" />
            <Legend />
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
};

// ═══ JURY VS PUBLIC ═══
const ViewJuryPublic = () => {
  const data = useMemo(computeJuryVsPublic, []);
  return (
    <div>
      <SectionTitle sub={"Le jury et le public sont-ils d\u2019accord ?"}>{"Jury vs Public"}</SectionTitle>
      <Table headers={["Année", "Jury (1er)", "Public (1er)", "Coïncidence"]}
        rows={data.map(d => [
          <strong>{d.year}</strong>, <Var>{d.jury}</Var>, d.public_choice,
          d.match ? <span style={{ color: "#3B6B3A", fontWeight: 700 }}>{"✔ Oui"}</span> : <span style={{ color: "#c0392b" }}>{"✘ Non"}</span>
        ])} goldFirst={false} />
      <InfoBox color="blue" title="Analyse">
        Sur 10 éditions, jury et public ne coïncident que <strong>2 fois</strong> (2015 avec <Var>Barbe Noire</Var>, 2022 partiellement avec <Var>Les Avenières</Var>). Le public privilégie les couleurs vives et les iris florifères, tandis que le jury récompense la morphologie, le branchement et l’originalité du coloris.
      </InfoBox>
    </div>
  );
};

// ═══ FRANCIRIS VS FLORENCE ═══
const ViewVsFlorence = () => {
  const compYears = [2000, 2005, 2007, 2011, 2015, 2017, 2019, 2022, 2024];
  const paired = compYears.map(y => {
    const fr = editions.find(e => e.year === y);
    const fl = florence.find(f => f.year === y);
    return { year: y, franciris: fr?.podium[0], florence: fl };
  }).filter(d => d.franciris && d.florence);
  const flCountry = {};
  florence.forEach(f => { flCountry[f.pays] = (flCountry[f.pays] || 0) + 1; });
  const flPie = Object.entries(flCountry).map(([pays, count]) => ({ pays, count })).sort((a,b) => b.count - a.count);
  return (
    <div>
      <SectionTitle sub={"Mêmes hybrideurs, mêmes années, résultats différents ?"}>{"Franciris vs Florence"}</SectionTitle>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1.5rem", marginBottom: "2rem" }}>
        <div>
          <h3 style={{ fontFamily: "'DM Sans',sans-serif", fontSize: "0.9rem", fontWeight: 800, color: "#000", marginBottom: "0.5rem" }}>{"Franciris \u2014 Victoires par pays"}</h3>
          <div style={{ height: 200 }}>
            <ResponsiveContainer>
              <PieChart><Pie data={computeCountryWins()} dataKey="count" nameKey="pays" cx="50%" cy="50%" outerRadius={70} label={({ pays, count }) => pays + " (" + count + ")"} style={{ fontSize: "0.7rem" }}>
                {computeCountryWins().map((d,i) => <Cell key={i} fill={COUNTRY_COLORS[d.pays] || "#999"} />)}
              </Pie><Tooltip /></PieChart>
            </ResponsiveContainer>
          </div>
        </div>
        <div>
          <h3 style={{ fontFamily: "'DM Sans',sans-serif", fontSize: "0.9rem", fontWeight: 800, color: "#000", marginBottom: "0.5rem" }}>{"Florence \u2014 Fiorino d\u2019Oro par pays"}</h3>
          <div style={{ height: 200 }}>
            <ResponsiveContainer>
              <PieChart><Pie data={flPie} dataKey="count" nameKey="pays" cx="50%" cy="50%" outerRadius={70} label={({ pays, count }) => pays + " (" + count + ")"} style={{ fontSize: "0.7rem" }}>
                {flPie.map((d,i) => <Cell key={i} fill={COUNTRY_COLORS[d.pays] || "#999"} />)}
              </Pie><Tooltip /></PieChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>
      <H3>{"Comparaison directe (années communes)"}</H3>
      <Table headers={["Année", "Franciris \u2014 GP", "Pays", "Florence \u2014 Fiorino", "Pays"]}
        rows={paired.map(d => [
          <strong>{d.year}</strong>,
          <Var>{d.franciris.cultivar}</Var>, <CFlag pays={d.franciris.pays} />,
          <Var>{d.florence.cultivar}</Var>, <CFlag pays={d.florence.pays} />,
        ])} goldFirst={false} />
      <InfoBox color="gold" title={"Seul double vainqueur confirmé"}>
        <Var>Chachar</Var> (Zdeněk Seidl) est le seul cultivar à avoir remporté les deux prix suprêmes européens : le Philippe de Vilmorin (Franciris 2017) et le Fiorino d’Oro (Florence 2019). <Var>High Desert</Var> (Keppel) a concouru aux deux : 2e à Franciris 2017, prix de la Meilleure variété précoce à Florence 2019.
      </InfoBox>
    </div>
  );
};

// ═══ RÉCOMPENSES CROISÉES ═══
const ViewAIS = () => (
  <div>
    <SectionTitle sub={"AIS Awards, Florence et Franciris : le fossé transatlantique"}>{"Récompenses croisées"}</SectionTitle>
    <Table headers={["Cultivar", "Hybrideur", "Pays", "HM", "AM", "Autre"]}
      rows={aisAwards.map(a => [
        <Var>{a.cultivar}</Var>, a.hybrideur, <CFlag pays={a.pays} />,
        a.hm ? <span style={{ color: "#3B6B3A", fontWeight: 700 }}>{a.hm}</span> : <span style={{ color: "#ccc" }}>{"\u2014"}</span>,
        a.am ? <span style={{ color: "#3B6B3A", fontWeight: 700 }}>{a.am}</span> : <span style={{ color: "#ccc" }}>{"\u2014"}</span>,
        a.other ? <strong style={{ color: GOLD }}>{a.other}</strong> : <span style={{ color: "#ccc" }}>{"\u2014"}</span>,
      ])} goldFirst={false} />
    <InfoBox color="accent" title={"Le fossé structurel"}>
      <strong>Tous les cultivars américains</strong> primés à Franciris ont reçu au minimum un HM. <strong>Aucun cultivar européen</strong> n’a obtenu la moindre récompense AIS. Le système AIS exige une évaluation dans des jardins nord-américains où les iris européens sont absents — c’est un problème de distribution, pas de qualité.
    </InfoBox>
    <H3>{"Trajectoire exceptionnelle : \u2018Marry The Night\u2019"}</H3>
    <div style={{ background: "#F7F5F0", borderRadius: 8, padding: "1.2rem", border: "1px solid #E8E2D8" }}>
      <div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
        {[
          { year: 2017, label: "Introduction" },
          { year: 2019, label: "HM + Franciris 2e" },
          { year: 2021, label: "AM" },
          { year: 2023, label: "Nelson Award" },
          { year: 2025, label: "Wister Medal" },
        ].map((s,i) => (
          <div key={i} style={{ flex: 1, minWidth: 100, textAlign: "center", padding: "0.6rem", background: "#fff", borderRadius: 6, border: "1px solid #E8E2D8" }}>
            <div style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: "1.3rem", fontWeight: 700, color: GOLD }}>{s.year}</div>
            <div style={{ fontSize: "0.75rem", fontWeight: 600, color: "#333" }}>{s.label}</div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ═══ MAIN APP ═══
const views = [
  { value: "overview", label: "Vue d\u2019ensemble", component: ViewOverview },
  { value: "palmares", label: "Palmar\u00e8s complet par \u00e9dition", component: ViewPalmares },
  { value: "geo", label: "Basculement g\u00e9opolitique", component: ViewGeo },
  { value: "hybrideurs", label: "Palmar\u00e8s par hybrideur", component: ViewHybrideurs },
  { value: "jurypublic", label: "Jury vs Public", component: ViewJuryPublic },
  { value: "florence", label: "Franciris vs Florence", component: ViewVsFlorence },
  { value: "ais", label: "R\u00e9compenses crois\u00e9es (AIS / Florence)", component: ViewAIS },
];

export default function App() {
  const [view, setView] = useState("overview");
  const Current = views.find(v => v.value === view)?.component || ViewOverview;
  return (
    <div style={{ fontFamily: "'DM Sans', sans-serif", background: "#FDFCF9", minHeight: "100vh", color: "#2D2A26" }}>
      <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,400;0,600;0,700;1,400;1,600;1,700&family=DM+Sans:ital,wght@0,400;0,500;0,700;1,400&display=swap" rel="stylesheet" />
      <header style={{ background: "linear-gradient(135deg, #FCEAA2 0%, #f5e08a 40%, #e8d06e 100%)", color: "#3a2e10", textAlign: "center", padding: "3rem 2rem 2.5rem", borderBottom: "3px solid " + GOLD }}>
        <div style={{ fontSize: "1.2rem", letterSpacing: "0.8rem", color: GOLD, opacity: 0.5, marginBottom: "0.8rem" }}>{"♉ ❦ ♉"}</div>
        <h1 style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: "clamp(1.6rem, 4.5vw, 2.6rem)", fontWeight: 700, lineHeight: 1.18, marginBottom: "0.4rem" }}>
          Franciris Analytics
        </h1>
        <p style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: "clamp(0.9rem, 2.2vw, 1.15rem)", fontStyle: "italic", color: "#5B6A8A", maxWidth: 600, margin: "0 auto" }}>
          {"Le tableau de bord du concours international d\u2019iris de Paris \u2014 10 \u00e9ditions \u00b7 2000\u20132024"}
        </p>
        <div style={{ display: "flex", gap: "0.5rem", justifyContent: "center", flexWrap: "wrap", marginTop: "1rem" }}>
          {["Palmar\u00e8s complets", "Analyse g\u00e9opolitique", "Franciris vs Florence", "R\u00e9compenses crois\u00e9es"].map(b => (
            <span key={b} style={{ display: "inline-block", fontFamily: "'DM Sans',sans-serif", fontSize: "0.68rem", fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase", border: "1.5px solid rgba(58,46,16,0.3)", padding: "0.28em 0.8em", borderRadius: 2, background: "rgba(255,255,255,0.4)" }}>{b}</span>
          ))}
        </div>
      </header>
      <NavSelect value={view} onChange={setView} options={views} />
      <div style={{ maxWidth: 960, margin: "0 auto", padding: "2.5rem 1.5rem 5rem" }}>
        <Current />
      </div>
      <footer style={{ background: BLUE, color: "rgba(255,255,255,0.65)", textAlign: "center", padding: "2rem 1.5rem", fontSize: "0.8rem", letterSpacing: "0.04em" }}>
        <strong style={{ color: "rgba(255,255,255,0.9)" }}>Franciris Analytics</strong>{" \u2014 SFIB \u00b7 L\u2019Iriseraie"}<br />
        {"Sources : iris-bulbeuses.org \u00b7 wiki.irises.org \u00b7 societaitalianairis.com \u00b7 Iris et Bulbeuses"}
      </footer>
    </div>
  );
}