// Shared visual components for Florilegio
const { useState } = React;

// ============ SVG Plant Illustrations (abstract, original) ============
const PlantArt = ({ plant, variant = 'card' }) => {
  // Foto reale caricata dal gestionale, se presente: sostituisce l'illustrazione generata
  if (plant.images?.length) {
    return <img src={plant.images[0]} alt={plant.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} loading="lazy" />;
  }
  // Pick a style by category for variety — all are abstract geometric botanical studies
  const cat = plant.cat;
  const seed = plant.id.split('').reduce((a, c) => a + c.charCodeAt(0), 0);
  const rng = (n) => ((seed * (n + 17) * 9301 + 49297) % 233280) / 233280;

  const palettes = {
    fogliame: ['#3a5a3a', '#6b7a5a', '#2a3e2a', '#a8b08e', '#ede4ce'],
    melastom: ['#4a3a5a', '#6b4a7a', '#a03a6b', '#c87fa3', '#ede4ce'],
    terrario: ['#3a5a4a', '#5a7a6b', '#87a090', '#b8502e', '#ede4ce'],
    succulente: ['#6b7a4a', '#8a9060', '#c79a3a', '#d97a56', '#f4e8cc'],
    statement: ['#2a3a4a', '#4a5a6b', '#6b7a8a', '#b8502e', '#ede4ce'],
    premium: ['#1a2018', '#3a4a3a', '#6b503a', '#c79a3a', '#ede4ce'],
  };
  const pal = palettes[cat] || palettes.fogliame;
  const bg = pal[4];

  // Different botanical motifs by category
  const motifs = {
    fogliame: 'monstera',
    melastom: 'ovate',
    terrario: 'small-round',
    succulente: 'rosette',
    statement: 'strap',
    premium: 'heart',
  };
  const motif = motifs[cat];

  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" xmlns="http://www.w3.org/2000/svg">
      <rect width="400" height="500" fill={bg} />
      {/* subtle grid texture */}
      <defs>
        <pattern id={`tex-${plant.id}`} width="40" height="40" patternUnits="userSpaceOnUse">
          <circle cx="20" cy="20" r=".6" fill={pal[1]} opacity=".15" />
        </pattern>
        <linearGradient id={`gr-${plant.id}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor={pal[0]} stopOpacity=".0" />
          <stop offset="1" stopColor={pal[0]} stopOpacity=".25" />
        </linearGradient>
      </defs>
      <rect width="400" height="500" fill={`url(#tex-${plant.id})`} />
      <rect width="400" height="500" fill={`url(#gr-${plant.id})`} />

      {motif === 'monstera' && <MonsteraMotif pal={pal} rng={rng} />}
      {motif === 'ovate' && <OvateMotif pal={pal} rng={rng} />}
      {motif === 'small-round' && <SmallRoundMotif pal={pal} rng={rng} />}
      {motif === 'rosette' && <RosetteMotif pal={pal} rng={rng} />}
      {motif === 'strap' && <StrapMotif pal={pal} rng={rng} />}
      {motif === 'heart' && <HeartMotif pal={pal} rng={rng} />}

      {/* label */}
      <text x="20" y="480" fill={pal[0]} opacity=".5" fontSize="8" fontFamily="monospace" letterSpacing="1">
        {plant.family.toUpperCase()}
      </text>
    </svg>
  );
};

// ============ Photo Gallery (foto multiple con miniature) ============
const PhotoGallery = ({ plant }) => {
  const [active, setActive] = useState(0);
  const images = plant.images || [];
  if (images.length <= 1) return <PlantArt plant={plant} variant="detail" />;
  return (
    <div className="d-gallery">
      <div className="d-gallery-main">
        <img src={images[active]} alt={plant.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </div>
      <div className="d-gallery-thumbs">
        {images.map((url, i) => (
          <button
            key={url}
            type="button"
            className={`d-gallery-thumb ${i === active ? 'active' : ''}`}
            onClick={() => setActive(i)}
            aria-label={`Foto ${i + 1} di ${plant.name}`}
          >
            <img src={url} alt="" loading="lazy" />
          </button>
        ))}
      </div>
    </div>
  );
};

const MonsteraMotif = ({ pal, rng }) => {
  // Large fenestrated leaf silhouette
  return (
    <g transform="translate(200 270) rotate(-8)">
      <ellipse cx="0" cy="0" rx="140" ry="180" fill={pal[0]} opacity=".92" />
      {/* fenestrations */}
      {[...Array(6)].map((_, i) => {
        const y = -120 + i * 42;
        const w = 60 - i * 4;
        return <ellipse key={i} cx={i % 2 ? -30 : 30} cy={y} rx={w} ry="14" fill={pal[4]} />;
      })}
      {/* midrib */}
      <line x1="0" y1="-175" x2="0" y2="175" stroke={pal[2]} strokeWidth="1.5" opacity=".6" />
      {/* stem */}
      <line x1="0" y1="180" x2="0" y2="240" stroke={pal[2]} strokeWidth="4" />
    </g>
  );
};

const OvateMotif = ({ pal, rng }) => {
  return (
    <g transform="translate(200 260)">
      {[0, 1, 2].map((i) => {
        const rot = -40 + i * 40;
        return (
          <g key={i} transform={`rotate(${rot})`}>
            <ellipse cx="0" cy="-70" rx="55" ry="100" fill={pal[i % 3]} opacity={0.85 - i * 0.1} />
            <line x1="0" y1="30" x2="0" y2="-160" stroke={pal[3]} strokeWidth="1" opacity=".5" />
          </g>
        );
      })}
      {/* purple underside hint */}
      <ellipse cx="0" cy="-70" rx="55" ry="100" fill="none" stroke={pal[2]} strokeWidth="2" opacity=".4" />
    </g>
  );
};

const SmallRoundMotif = ({ pal, rng }) => {
  // cluster of small round leaves
  const leaves = [];
  for (let i = 0; i < 14; i++) {
    const x = 60 + rng(i) * 280;
    const y = 100 + rng(i + 5) * 300;
    const r = 18 + rng(i + 9) * 22;
    leaves.push(
      <g key={i}>
        <circle cx={x} cy={y} r={r} fill={pal[Math.floor(rng(i + 2) * 3)]} opacity=".85" />
        <circle cx={x - r * 0.3} cy={y - r * 0.3} r={r * 0.25} fill={pal[4]} opacity=".4" />
      </g>
    );
  }
  return <g>{leaves}</g>;
};

const RosetteMotif = ({ pal, rng }) => {
  // concentric rosette
  const ring = (radius, n, colorIdx, scaleY = 1) => {
    const pts = [];
    for (let i = 0; i < n; i++) {
      const a = (i / n) * Math.PI * 2;
      const cx = 200 + Math.cos(a) * radius;
      const cy = 260 + Math.sin(a) * radius * scaleY;
      pts.push(
        <ellipse
          key={i}
          cx={cx}
          cy={cy}
          rx="32"
          ry="56"
          fill={pal[colorIdx]}
          opacity=".88"
          transform={`rotate(${(a * 180) / Math.PI + 90} ${cx} ${cy})`}
        />
      );
    }
    return pts;
  };
  return (
    <g>
      {ring(90, 9, 1)}
      {ring(55, 7, 0)}
      {ring(25, 5, 2)}
      <circle cx="200" cy="260" r="14" fill={pal[3]} />
    </g>
  );
};

const StrapMotif = ({ pal, rng }) => {
  // tall strap-like leaves
  return (
    <g transform="translate(200 260)">
      {[-60, -20, 20, 60].map((x, i) => (
        <g key={i} transform={`translate(${x} 0) rotate(${x * 0.15})`}>
          <path
            d={`M 0 100 Q -25 0 -12 -140 Q 0 -170 12 -140 Q 25 0 0 100 Z`}
            fill={pal[i % 3]}
            opacity=".88"
          />
          <line x1="0" y1="100" x2="0" y2="-160" stroke={pal[4]} strokeWidth="1.5" opacity=".6" />
        </g>
      ))}
    </g>
  );
};

const HeartMotif = ({ pal, rng }) => {
  // heart-shaped leaf
  return (
    <g transform="translate(200 260)">
      <path
        d="M 0 140 C 120 40 140 -60 80 -110 C 40 -140 10 -120 0 -90 C -10 -120 -40 -140 -80 -110 C -140 -60 -120 40 0 140 Z"
        fill={pal[0]}
        opacity=".92"
      />
      {/* veins */}
      {[...Array(5)].map((_, i) => {
        const a = (-60 + i * 30) * (Math.PI / 180);
        return (
          <line
            key={i}
            x1="0"
            y1="-60"
            x2={Math.cos(a) * 100}
            y2={-60 + Math.sin(a) * 100}
            stroke={pal[4]}
            strokeWidth="1.5"
            opacity=".6"
          />
        );
      })}
      <line x1="0" y1="-90" x2="0" y2="130" stroke={pal[4]} strokeWidth="2" opacity=".7" />
    </g>
  );
};

// ============ Icons ============
const Icon = ({ name, size = 16 }) => {
  const icons = {
    search: <><circle cx="11" cy="11" r="7" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></>,
    cart: <><circle cx="9" cy="21" r="1" /><circle cx="20" cy="21" r="1" /><path d="M1 1h4l2.7 13.4a2 2 0 0 0 2 1.6h9.7a2 2 0 0 0 2-1.6L23 6H6" /></>,
    user: <><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" /></>,
    heart: <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />,
    plus: <><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></>,
    minus: <line x1="5" y1="12" x2="19" y2="12" />,
    close: <><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></>,
    x: <><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></>,
    arrow: <><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></>,
    arrow_left: <><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></>,
    arrow_right: <polyline points="9 18 15 12 9 6" />,
    alert: <><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></>,
    lock: <><rect x="3" y="11" width="18" height="11" rx="2" ry="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></>,
    share: <><circle cx="18" cy="5" r="3" /><circle cx="6" cy="12" r="3" /><circle cx="18" cy="19" r="3" /><line x1="8.59" y1="13.51" x2="15.42" y2="17.49" /><line x1="15.41" y1="6.51" x2="8.59" y2="10.49" /></>,
    sun: <><circle cx="12" cy="12" r="4" /><line x1="12" y1="2" x2="12" y2="4" /><line x1="12" y1="20" x2="12" y2="22" /><line x1="4.93" y1="4.93" x2="6.34" y2="6.34" /><line x1="17.66" y1="17.66" x2="19.07" y2="19.07" /><line x1="2" y1="12" x2="4" y2="12" /><line x1="20" y1="12" x2="22" y2="12" /><line x1="4.93" y1="19.07" x2="6.34" y2="17.66" /><line x1="17.66" y1="6.34" x2="19.07" y2="4.93" /></>,
    droplet: <path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z" />,
    thermo: <path d="M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0z" />,
    watering: <><path d="M5 10h10l3 3v4a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2z" /><path d="M18 13l4-3-4-3" /></>,
    soil: <><path d="M2 20h20" /><path d="M4 20v-6l4-2 4 3 4-4 4 2v7" /></>,
    propagation: <><circle cx="12" cy="5" r="3" /><line x1="12" y1="8" x2="12" y2="20" /><path d="M8 14c0-2 2-4 4-4s4 2 4 4" /></>,
    info: <><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><circle cx="12" cy="16" r=".5" fill="currentColor" /></>,
    grid: <><rect x="3" y="3" width="7" height="7" /><rect x="14" y="3" width="7" height="7" /><rect x="3" y="14" width="7" height="7" /><rect x="14" y="14" width="7" height="7" /></>,
    list: <><line x1="8" y1="6" x2="21" y2="6" /><line x1="8" y1="12" x2="21" y2="12" /><line x1="8" y1="18" x2="21" y2="18" /><circle cx="4" cy="6" r="1" /><circle cx="4" cy="12" r="1" /><circle cx="4" cy="18" r="1" /></>,
    check: <polyline points="20 6 9 17 4 12" />,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      {icons[name]}
    </svg>
  );
};

// ============ Logo ============
const Logo = () => (
  <svg width="26" height="26" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
    <circle cx="20" cy="20" r="19" stroke="currentColor" strokeWidth=".8" />
    <path d="M20 8 C 26 14 26 26 20 32 C 14 26 14 14 20 8 Z" fill="currentColor" />
    <line x1="20" y1="8" x2="20" y2="32" stroke="#f4f0e8" strokeWidth=".8" />
  </svg>
);

// ============ Condizioni di coltivazione ============
// Le schede descrivono luce e umidità a parole ("Luce indiretta bassa-media",
// "70–85%"). Qui quei testi diventano categorie confrontabili, per poterci
// filtrare sopra. Le regole ricalcano i valori realmente presenti a catalogo:
// se in futuro venissero scritte diciture diverse, andranno estese qui.

// Una pianta può appartenere a più fasce: "bassa-media" tollera entrambe,
// ed è giusto che compaia cercando l'una o l'altra.
const luciDi = (plant) => {
  const t = String(plant.light || '').toLowerCase();
  const fasce = [];
  // "mai sole diretto" contiene "sole diretto": senza questo controllo
  // finirebbe fra le piante da pieno sole, cioè l'esatto contrario.
  const vietaSole = /mai sole diretto|no sole diretto|senza sole diretto/.test(t);
  if (/bassa|ombreggiat|sottobosco/.test(t)) fasce.push('bassa');
  if (/media/.test(t)) fasce.push('media');
  if (/brillante|alta/.test(t)) fasce.push('brillante');
  // "indiretta" contiene "diretta": si cercano le sole forme esplicite
  if (!vietaSole && /sole diretto|luce diretta/.test(t)) fasce.push('sole');
  return fasce.length ? fasce : ['media'];
};

// Dall'intervallo "70–85%" si prende il minimo: è la soglia sotto la quale la
// pianta inizia a soffrire, quindi ciò che il cliente deve poter garantire.
const umiditaDi = (plant) => {
  const m = String(plant.humidity || '').match(/(\d+)/);
  const min = m ? parseInt(m[1], 10) : 60;
  if (min >= 75) return 'teca';     // serve una teca o una serra
  if (min >= 60) return 'alta';     // umidificatore o bagno luminoso
  return 'normale';                 // sopravvive in un appartamento comune
};

const ETICHETTE_LUCE = {
  bassa: 'Poca luce', media: 'Luce media', brillante: 'Molto luminoso', sole: 'Sole diretto',
};
const ETICHETTE_UMIDITA = {
  normale: 'Casa normale', alta: 'Umidità alta', teca: 'Teca o serra',
};

// Testo su cui cerca la ricerca del sito. Include le condizioni di coltivazione:
// prima si cercava solo fra nome, famiglia, provenienza e note, quindi "poca
// luce" o "ombra" non restituivano nulla pur essendo dati presenti su ogni scheda.
const testoRicercabile = (plant, categorie = []) => {
  const cat = categorie.find(c => c.id === plant.cat);
  return [
    plant.name, plant.family, plant.origin, plant.notes,
    plant.light, plant.humidity, plant.temp, plant.water, plant.soil, plant.prop,
    cat?.title, cat?.subtitle,
    // sinonimi che un cliente usa ma che non compaiono nelle schede
    ...luciDi(plant).map(l => ETICHETTE_LUCE[l]),
    ETICHETTE_UMIDITA[umiditaDi(plant)],
    umiditaDi(plant) === 'normale' ? 'facile principiante senza teca' : '',
    umiditaDi(plant) === 'teca' ? 'difficile esigente' : '',
    luciDi(plant).includes('bassa') ? 'ombra poca luce nord' : '',
  ].filter(Boolean).join(' ').toLowerCase();
};

const cercaPiante = (piante, query, categorie = []) => {
  const q = String(query || '').trim().toLowerCase();
  if (!q) return piante;
  // Ogni parola deve comparire: "begonia ombra" restringe invece di allargare
  const parole = q.split(/\s+/);
  return piante.filter(p => {
    const testo = testoRicercabile(p, categorie);
    return parole.every(w => testo.includes(w));
  });
};

Object.assign(window, {
  PlantArt, PhotoGallery, Icon, Logo,
  luciDi, umiditaDi, ETICHETTE_LUCE, ETICHETTE_UMIDITA, testoRicercabile, cercaPiante,
});
