// Botanical illustration florals that grow up from the page edges over time.
// Stems are sage green; blooms in lavender / poppy / yellow. Time-based progress
// runs while the user is on the page (persisted across same-session refreshes).

const { useEffect, useState } = React;

function useTimeProgress(durationMs = 120000) {
  const [p, setP] = useState(0);
  useEffect(() => {
    const key = "picara_flora_started_at";
    let started = parseInt(sessionStorage.getItem(key) || "0", 10);
    if (!started || Date.now() - started > durationMs * 6) {
      started = Date.now();
      sessionStorage.setItem(key, String(started));
    }
    let raf;
    function tick() {
      const elapsed = Date.now() - started;
      const next = Math.min(1, elapsed / durationMs);
      setP(next);
      if (next < 1) raf = requestAnimationFrame(tick);
    }
    tick();
    return () => raf && cancelAnimationFrame(raf);
  }, [durationMs]);
  return p;
}

function localProgress(p, start, end) {
  const local = Math.min(1, Math.max(0, (p - start) / Math.max(0.001, end - start)));
  return 1 - Math.pow(1 - local, 2.2);
}

function dashStyle(L, t) {
  return {
    strokeDasharray: L,
    strokeDashoffset: L * (1 - t),
  };
}

// SVG viewBox is 400 x 1200; baseline (ground) is y=1200, plants reach toward y=0.
const BASE = 1200;

// === LAVENDER ===
function LavenderStem({ p, x, scale = 1, start = 0, end = 1, height = 1000 }) {
  const tStem = localProgress(p, start, Math.min(1, start + (end - start) * 0.55));
  const tLeaves = localProgress(p, start + (end - start) * 0.1, end);
  const stemD = `M 0 0 C -3 ${-height * 0.18}, 6 ${-height * 0.36}, 0 ${-height * 0.55} S -8 ${-height * 0.78}, 0 ${-height * 0.92}`;
  const stemLen = height * 1.05;
  const headStartY = -height * 0.66;
  return (
    <g transform={`translate(${x}, ${BASE}) scale(${scale})`}>
      <path className="stem" d={stemD} style={dashStyle(stemLen, tStem)} />
      <path className="leaf" d={`M 0 ${-height * 0.28} q -22 -10 -34 -34`} style={dashStyle(60, tLeaves)} />
      <path className="leaf" d={`M 0 ${-height * 0.36} q 24 -8 34 -32`} style={dashStyle(60, tLeaves)} />
      <path className="leaf" d={`M 0 ${-height * 0.48} q -26 -6 -38 -28`} style={dashStyle(60, tLeaves)} />
      {Array.from({ length: 16 }).map((_, i) => {
        const yy = headStartY - i * 16;
        const alt = i % 2 === 0 ? 1 : -1;
        const tBud = localProgress(
          p,
          start + (end - start) * (0.4 + i * 0.018),
          Math.min(1, start + (end - start) * (0.55 + i * 0.018))
        );
        return (
          <g key={i} style={{ opacity: tBud }}>
            <ellipse
              cx={alt * 6}
              cy={yy}
              rx={6}
              ry={9}
              fill="var(--lavender)"
              stroke="var(--charcoal)"
              strokeWidth="1"
              transform={`scale(${0.4 + tBud * 0.6})`}
              style={{ transformOrigin: `${alt * 6}px ${yy}px` }}
            />
          </g>
        );
      })}
    </g>
  );
}

// === POPPY ===
function Poppy({ p, x, scale = 1, start = 0, end = 1, height = 1000, color = "var(--poppy)" }) {
  const tStem = localProgress(p, start, Math.min(1, start + (end - start) * 0.55));
  const tBud = localProgress(p, start + (end - start) * 0.45, Math.min(1, start + (end - start) * 0.6));
  const tBloom = localProgress(p, start + (end - start) * 0.6, end);
  const stemD = `M 0 0 C 8 ${-height * 0.18}, -10 ${-height * 0.36}, 4 ${-height * 0.55} S -6 ${-height * 0.78}, 2 ${-height * 0.94}`;
  const stemLen = height * 1.05;
  const headY = -height * 0.94;
  return (
    <g transform={`translate(${x}, ${BASE}) scale(${scale})`}>
      <path className="stem" d={stemD} style={dashStyle(stemLen, tStem)} />
      {Array.from({ length: 14 }).map((_, i) => {
        const yy = -height * 0.12 - i * (height * 0.05);
        const tt = localProgress(p, start + (end - start) * (0.1 + i * 0.025), end);
        return (
          <path
            key={i}
            className="leaf"
            d={`M ${i % 2 === 0 ? -2 : 2} ${yy} l ${i % 2 === 0 ? -10 : 10} -4`}
            style={dashStyle(14, tt)}
          />
        );
      })}
      <path
        className="leaf"
        d={`M 0 ${-height * 0.22} q -28 -4 -42 -22 q -6 18 8 36 q 16 8 34 -14`}
        style={dashStyle(160, localProgress(p, start + (end - start) * 0.2, end))}
      />
      <g transform={`translate(2 ${headY})`}>
        <path className="leaf" d="M -10 4 q 10 -10 22 0" style={dashStyle(22, tBud)} />
        <g
          style={{
            opacity: tBloom,
            transformOrigin: "0 0",
            transform: `scale(${0.3 + tBloom * 0.7})`,
            transition: "transform 0.2s linear",
          }}
        >
          <path
            d="M -36 -8 C -42 -36, -22 -64, -2 -56 C 18 -64, 38 -38, 32 -8 C 24 6, -24 6, -36 -8 Z"
            fill={color}
            stroke="var(--charcoal)"
            strokeWidth="1.2"
          />
          <path
            d="M -22 -22 C -16 -34, -4 -38, 0 -28 C 4 -38, 18 -32, 22 -22"
            fill="none"
            stroke="var(--charcoal)"
            strokeWidth="0.8"
            opacity="0.6"
          />
          <circle cx="-2" cy="-12" r="3" fill="var(--charcoal)" />
          <path d="M -2 -12 l -8 -10 M -2 -12 l 0 -12 M -2 -12 l 8 -10" stroke="var(--charcoal)" strokeWidth="0.8" />
        </g>
      </g>
    </g>
  );
}

// === FERN ===
function Fern({ p, x, scale = 1, start = 0, end = 1, height = 900 }) {
  const tStem = localProgress(p, start, Math.min(1, start + (end - start) * 0.85));
  const stemD = `M 0 0 C 4 ${-height * 0.16}, -4 ${-height * 0.4}, 2 ${-height * 0.62} S -2 ${-height * 0.85}, 0 ${-height}`;
  const stemLen = height * 1.05;
  const fronds = Math.round(height / 32);
  return (
    <g transform={`translate(${x}, ${BASE}) scale(${scale})`}>
      <path className="stem" d={stemD} style={dashStyle(stemLen, tStem)} />
      {Array.from({ length: fronds }).map((_, i) => {
        const yy = -40 - i * 32;
        const len = 28 + Math.sin(i * 0.6) * 8;
        const sideDir = i % 2 === 0 ? 1 : -1;
        const tt = localProgress(p, start + (end - start) * (0.05 + i * 0.018), end);
        return (
          <path
            key={i}
            className="leaf"
            d={`M 0 ${yy} q ${sideDir * len * 0.6} ${-len * 0.2}, ${sideDir * len} ${-len * 0.5}`}
            style={dashStyle(len * 1.3, tt)}
          />
        );
      })}
    </g>
  );
}

// === Yellow daisy ===
function YellowBloom({ p, x, scale = 1, start = 0, end = 1, height = 850 }) {
  const tStem = localProgress(p, start, Math.min(1, start + (end - start) * 0.55));
  const tOpen = localProgress(p, start + (end - start) * 0.55, end);
  const stemD = `M 0 0 C -6 ${-height * 0.16}, 8 ${-height * 0.38}, -4 ${-height * 0.58} S 4 ${-height * 0.82}, 0 ${-height}`;
  const stemLen = height * 1.05;
  const headY = -height;
  return (
    <g transform={`translate(${x}, ${BASE}) scale(${scale})`}>
      <path className="stem" d={stemD} style={dashStyle(stemLen, tStem)} />
      <path
        className="leaf"
        d={`M -2 ${-height * 0.3} q -22 -8 -32 -26`}
        style={dashStyle(50, localProgress(p, start + (end - start) * 0.2, end))}
      />
      <path
        className="leaf"
        d={`M 2 ${-height * 0.5} q 22 -6 32 -28`}
        style={dashStyle(50, localProgress(p, start + (end - start) * 0.3, end))}
      />
      <g
        style={{
          opacity: tOpen,
          transform: `translate(0px, ${headY}px) scale(${0.3 + tOpen * 0.7})`,
          transformOrigin: `0px ${headY}px`,
          transition: "transform 0.2s linear",
        }}
      >
        {Array.from({ length: 8 }).map((_, i) => {
          const a = (i / 8) * Math.PI * 2;
          const cx = Math.cos(a) * 14;
          const cy = Math.sin(a) * 14;
          return (
            <ellipse
              key={i}
              cx={cx}
              cy={cy}
              rx={5}
              ry={11}
              transform={`rotate(${(a * 180) / Math.PI} ${cx} ${cy})`}
              fill="var(--yellow)"
              stroke="var(--charcoal)"
              strokeWidth="1"
            />
          );
        })}
        <circle cx="0" cy="0" r="6" fill="var(--poppy-deep)" stroke="var(--charcoal)" strokeWidth="1" />
      </g>
    </g>
  );
}

// === Forget-me-not ===
// A slender stem with small clusters of 5-petaled pale-blue flowers (yellow center).
function ForgetMeNot({ p, x, scale = 1, start = 0, end = 1, height = 600 }) {
  const tStem = localProgress(p, start, Math.min(1, start + (end - start) * 0.5));
  const stemD = `M 0 0 C 4 ${-height * 0.18}, -6 ${-height * 0.4}, 3 ${-height * 0.62} S -3 ${-height * 0.85}, 0 ${-height}`;
  const stemLen = height * 1.05;

  // A few clusters along the upper portion of the stem
  const clusters = [
    { y: -height * 0.55, side: 1, n: 5, t0: 0.5 },
    { y: -height * 0.72, side: -1, n: 6, t0: 0.6 },
    { y: -height * 0.88, side: 1, n: 5, t0: 0.72 },
    { y: -height * 1.0, side: 0, n: 7, t0: 0.82 },
  ];

  return (
    <g transform={`translate(${x}, ${BASE}) scale(${scale})`}>
      <path className="stem" d={stemD} style={dashStyle(stemLen, tStem)} />
      {/* small leaves on the lower stem */}
      <path
        className="leaf"
        d={`M 0 ${-height * 0.25} q -16 -6 -22 -22`}
        style={dashStyle(40, localProgress(p, start + (end - start) * 0.15, end))}
      />
      <path
        className="leaf"
        d={`M 0 ${-height * 0.4} q 16 -6 22 -22`}
        style={dashStyle(40, localProgress(p, start + (end - start) * 0.22, end))}
      />
      {clusters.map((c, ci) => {
        const cx0 = c.side * (height * 0.025);
        return (
          <g key={ci} transform={`translate(${cx0} ${c.y})`}>
            {Array.from({ length: c.n }).map((_, i) => {
              // distribute petals around a small radius
              const r = 14 + (i % 2) * 4;
              const a = (i / c.n) * Math.PI * 2 + ci * 0.7;
              const fx = Math.cos(a) * r;
              const fy = Math.sin(a) * r * 0.6;
              const tF = localProgress(
                p,
                start + (end - start) * (c.t0 + i * 0.012),
                Math.min(1, start + (end - start) * (c.t0 + 0.15 + i * 0.012))
              );
              return (
                <g
                  key={i}
                  transform={`translate(${fx} ${fy}) scale(${0.3 + tF * 0.7})`}
                  style={{ opacity: tF, transformOrigin: `${fx}px ${fy}px` }}
                >
                  {/* 5 petals as rounded ellipses around a center */}
                  {Array.from({ length: 5 }).map((_, pi) => {
                    const pa = (pi / 5) * Math.PI * 2 - Math.PI / 2;
                    const px = Math.cos(pa) * 4;
                    const py = Math.sin(pa) * 4;
                    return (
                      <circle
                        key={pi}
                        cx={px}
                        cy={py}
                        r={3.5}
                        fill="var(--forget)"
                        stroke="var(--charcoal)"
                        strokeWidth="0.6"
                      />
                    );
                  })}
                  {/* yellow center */}
                  <circle cx="0" cy="0" r="1.8" fill="var(--yellow)" stroke="var(--charcoal)" strokeWidth="0.5" />
                </g>
              );
            })}
          </g>
        );
      })}
    </g>
  );
}


function FloraSide({ side = "left" }) {
  const p = useTimeProgress(120000); // ~2 minutes to fully bloom
  const leftPlants = (
    <>
      <Fern p={p} x={28} scale={0.7} start={0.0} end={0.55} height={310} />
      <LavenderStem p={p} x={96} scale={0.9} start={0.0} end={0.7} height={390} />
      <Poppy p={p} x={172} scale={0.9} start={0.05} end={0.75} height={380} />
      <YellowBloom p={p} x={234} scale={0.75} start={0.15} end={0.85} height={310} />
      <Fern p={p} x={332} scale={0.6} start={0.25} end={0.95} height={280} />
    </>
  );

  const rightPlants = (
    <>
      <Fern p={p} x={50} scale={0.6} start={0.05} end={0.6} height={280} />
      <Poppy p={p} x={104} scale={0.85} start={0.0} end={0.7} height={380} />
      <LavenderStem p={p} x={196} scale={0.9} start={0.05} end={0.75} height={390} />
      <YellowBloom p={p} x={258} scale={0.8} start={0.18} end={0.9} height={320} />
      <Fern p={p} x={344} scale={0.55} start={0.3} end={0.95} height={290} />
    </>
  );

  return (
    <div className={`flora flora--${side}`} aria-hidden="true">
      <svg viewBox="0 0 400 1200" preserveAspectRatio="xMidYMax slice">
        {side === "left" ? leftPlants : rightPlants}
      </svg>
    </div>
  );
}

window.FloraSide = FloraSide;
window.useTimeProgress = useTimeProgress;
