/* global React */
const { useState, useEffect, useRef } = React;

// Animated demo: pricebook (back) + takeoff (back) → quote (front)
// Cycles every 6s. The two back cards "feed" the quote card via streamed lines.

function HeroDemo() {
  const [phase, setPhase] = useState(0); // 0 idle, 1 streaming, 2 quote built

  useEffect(() => {
    const seq = [
      { p: 0, t: 600 },
      { p: 1, t: 2200 },
      { p: 2, t: 3200 },
    ];
    let i = 0;
    let timer;
    const run = () => {
      const step = seq[i % seq.length];
      setPhase(step.p);
      timer = setTimeout(() => { i++; run(); }, step.t);
    };
    run();
    return () => clearTimeout(timer);
  }, []);

  // Pricebook items
  const pbItems = [
    ["Colorsteel Endura roof", "m²", "$78.50"],
    ["Decramastic tile", "m²", "$112.00"],
    ["Marley spouting 125", "lm",  "$24.30"],
    ["Dimond fascia 150", "lm", "$18.90"],
    ["Roofing screws 65mm", "box", "$42.60"],
    ["Butynol membrane", "m²", "$96.20"],
    ["Underlay synthetic", "roll", "$185.00"],
  ];

  // Takeoff measurements
  const toItems = [
    ["Main roof area", "248 m²"],
    ["Spouting linear", "62 lm"],
    ["Fascia run", "62 lm"],
    ["Ridge cap", "18 lm"],
    ["Valley flashing", "12 lm"],
    ["Penetrations", "4 ea"],
  ];

  return (
    <div className="demo-wrap">
      {/* Back-left: Pricebook */}
      <div className="demo-card pb-card" style={{
        opacity: phase >= 2 ? 0.35 : 1,
        transition: "opacity 0.6s var(--ease-out-quint), transform 0.6s var(--ease-out-quint)",
        transform: phase >= 2 ? "rotate(-5deg) translateX(-8px)" : "rotate(-3deg)",
      }}>
        <div className="demo-card-head">
          <span className="demo-card-title">Pricebook · Roofing.csv</span>
          <span className="demo-card-dot" />
        </div>
        <div style={{ overflow: "hidden", height: "calc(100% - 41px)" }}>
          {pbItems.map((r, i) => (
            <div key={i} className="pb-row" style={{
              animation: `slideInLeft 0.5s var(--ease-out-quint) ${i * 0.06}s both`,
            }}>
              <span>{r[0]}</span>
              <span className="qty">{r[1]}</span>
              <span className="price">{r[2]}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Back-right: Takeoff */}
      <div className="demo-card to-card" style={{
        opacity: phase >= 2 ? 0.35 : 1,
        transition: "opacity 0.6s var(--ease-out-quint), transform 0.6s var(--ease-out-quint)",
        transform: phase >= 2 ? "rotate(4.5deg) translateX(8px)" : "rotate(2.5deg)",
      }}>
        <div className="demo-card-head">
          <span className="demo-card-title">Takeoff · 14 Beach Rd</span>
          <span className="demo-card-dot" />
        </div>
        <div className="to-grid">
          {toItems.map((r, i) => (
            <div key={i} className="to-row" style={{
              animation: `slideInRight 0.5s var(--ease-out-quint) ${0.15 + i * 0.07}s both`,
            }}>
              <span>{r[0]}</span>
              <span className="num">{r[1]}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Stream lines (visualize data flowing into quote) */}
      <svg className="stream" viewBox="0 0 600 540" preserveAspectRatio="none">
        <defs>
          <linearGradient id="streamGrad" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" stopColor="rgba(255,107,26,0)" />
            <stop offset="50%" stopColor="rgba(255,107,26,0.65)" />
            <stop offset="100%" stopColor="rgba(255,107,26,0)" />
          </linearGradient>
        </defs>
        {phase === 1 && (
          <>
            {[0, 1, 2, 3].map(i => (
              <path
                key={"L"+i}
                d={`M ${80 + i*40} 200 Q ${200 + i*30} ${300 + i*15} 300 ${440 - i*20}`}
                fill="none"
                stroke="url(#streamGrad)"
                strokeWidth="1.5"
                strokeDasharray="4 8"
                style={{
                  animation: `dashFlow 0.9s linear ${i * 0.08}s infinite`,
                }}
              />
            ))}
            {[0, 1, 2, 3].map(i => (
              <path
                key={"R"+i}
                d={`M ${520 - i*40} 220 Q ${420 - i*30} ${320 + i*15} 300 ${440 - i*20}`}
                fill="none"
                stroke="url(#streamGrad)"
                strokeWidth="1.5"
                strokeDasharray="4 8"
                style={{
                  animation: `dashFlow 0.9s linear ${i * 0.08 + 0.1}s infinite`,
                }}
              />
            ))}
          </>
        )}
      </svg>

      {/* Front: Quote card */}
      <div className="demo-card q-card" style={{
        opacity: phase >= 2 ? 1 : 0.0,
        transform: phase >= 2 ? "translateY(0) scale(1)" : "translateY(40px) scale(0.96)",
        transition: "opacity 0.6s var(--ease-out-quint), transform 0.6s var(--ease-out-quint)",
        animation: phase >= 2 ? "floatY 4s ease-in-out 0.8s infinite" : "none",
      }}>
        <div className="demo-card-head">
          <span className="demo-card-title">Quote · QT-2049</span>
          <CheckBadge />
        </div>
        <div className="q-card-body">
          <div className="q-card-customer">Customer</div>
          <div className="q-card-name">David &amp; Sarah Brown</div>
          <div className="q-card-job">14 Beach Rd, Mt Maunganui · Re-roof</div>

          <div style={{ marginTop: 14 }}>
            <QLine label="Materials (248 m² Endura)" val="$19,468" delay={0.1} show={phase >= 2} />
            <QLine label="Spouting + fascia (62 lm)" val="$2,679" delay={0.2} show={phase >= 2} />
            <QLine label="Flashings + screws" val="$1,210" delay={0.3} show={phase >= 2} />
            <QLine label="Labour (4 days, 2 crew)" val="$8,400" delay={0.4} show={phase >= 2} />
          </div>

          <div className="q-total" style={{
            opacity: phase >= 2 ? 1 : 0,
            transform: phase >= 2 ? "translateY(0)" : "translateY(8px)",
            transition: "opacity 0.4s ease 0.6s, transform 0.4s var(--ease-out-quint) 0.6s",
          }}>
            <span className="qlbl">Total ex GST</span>
            <span className="qval"><span className="currency">NZ$</span>31,757</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function QLine({ label, val, delay, show }) {
  return (
    <div className="q-line" style={{
      opacity: show ? 1 : 0,
      transform: show ? "translateY(0)" : "translateY(6px)",
      transition: `opacity 0.4s ease ${delay}s, transform 0.4s var(--ease-out-quint) ${delay}s`,
    }}>
      <span className="qlbl">{label}</span>
      <span className="qval">{val}</span>
    </div>
  );
}

function CheckBadge() {
  return (
    <div style={{
      width: 18, height: 18, borderRadius: "50%",
      background: "var(--orange)", display: "flex",
      alignItems: "center", justifyContent: "center",
      color: "#0A0A0B",
    }}>
      <svg viewBox="0 0 16 16" width="10" height="10" fill="none" stroke="currentColor" strokeWidth="2.5">
        <path d="M3.5 8.5l3 3 6-7"/>
      </svg>
    </div>
  );
}

window.HeroDemo = HeroDemo;
