// Kotleto · ORDER TRACKING — interactive timeline with live map snippet

// One animated value drives the timeline, both route fills and both riders.
function useTrackingProgress(target, orderId) {
  const [displayed, setDisplayed] = useState(0);
  const current = useRef(0);
  const previousOrder = useRef(orderId);

  useEffect(() => {
    if (previousOrder.current !== orderId) {
      previousOrder.current = orderId;
      current.current = 0;
      setDisplayed(0);
    }
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      current.current = target;
      setDisplayed(target);
      return;
    }

    const from = current.current;
    const startedAt = performance.now();
    const duration = Math.abs(target - from) > .05 ? 850 : 450;
    let frame;
    const animate = time => {
      const fraction = Math.min(1, (time - startedAt) / duration);
      const eased = 1 - Math.pow(1 - fraction, 3);
      const next = Math.max(0, Math.min(1, fraction === 1 ? target : from + (target - from) * eased));
      current.current = next;
      setDisplayed(next);
      if (fraction < 1) frame = requestAnimationFrame(animate);
    };
    frame = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(frame);
  }, [target, orderId]);

  return displayed;
}

function Tracking({ accent = "#D9461E" }) {
  const { lang } = useLang();
  const { order, statusOverride } = useOrder();
  const [now, setNow] = useState(Date.now());

  useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);

  const elapsed = Math.max(0, now - (Number(order.placedAt) || now));
  const eta = Math.max(1, Number(order.eta) || 20 * 60 * 1000);
  const timeProgress = Math.max(0, Math.min(elapsed / eta, 1));
  const statusRanges = {
    new: [0, .15], placed: [0, .15], preparing: [.15, .45],
    packed: [.45, .7], out: [.7, 1], delivered: [1, 1],
  };
  const range = statusRanges[statusOverride];
  const targetProgress = order.status === "delivered" || statusOverride === "delivered"
    ? 1
    : range ? Math.min(range[1] - .001, Math.max(range[0], timeProgress)) : timeProgress;
  const progress = useTrackingProgress(targetProgress, order.id);
  const remainingMs = targetProgress === 1 ? 0 : Math.max(eta - elapsed, 0);
  const remainingMin = Math.ceil(remainingMs / 60000);

  const steps = [
    { key: "placed",    fa: "ثبت و تأیید شد",   en: "Confirmed",  ic: <Ico.Check />,   at: 0.0 },
    { key: "preparing", fa: "در حال آماده‌سازی", en: "Preparing",  ic: <Ico.Fire />,    at: 0.15 },
    { key: "packed",    fa: "بسته‌بندی سفارش",   en: "Packed",     ic: <Ico.Package />, at: 0.45 },
    { key: "out",       fa: "تحویل به پیک",      en: "On the way", ic: <Ico.Scooter />, at: 0.7 },
    { key: "delivered", fa: "تحویل به شما",      en: "Delivered",  ic: <Ico.Home />,    at: 1.0 },
  ];
  const activeIdx = steps.findLastIndex(s => progress >= s.at);
  const currentStep = steps[Math.max(activeIdx, 0)];
  const progressValue = Math.max(0, Math.min(progress * 100, 100));
  const progressPercent = progress === 1 ? 100 : Math.min(99, Math.round(progressValue));

  return (
    <section id="track" style={{ padding: "100px 0" }}>
      <Wrap className="wrap-pad">
        <SectionTitle
          eyebrow={{ fa: "پیگیری زنده", en: "Live tracking" }}
          title={{ fa: "سفارشت کجاست؟", en: "Where's your order?" }}
          sub={{ fa: "از لحظه‌ای که می‌زنی «ثبت سفارش» تا برسه دستت، هر دقیقه می‌دونی کجاست.", en: "From tap to doorstep, you'll know where it is every minute." }}
          accent={accent}
        />

        <div className="grid grid-track" style={{
          marginTop: 40,
          background: "var(--paper)", border: "1.5px solid var(--ink)", borderRadius: 32,
          boxShadow: "0 8px 0 var(--ink)",
          overflow: "hidden",
        }}>
          {/* LEFT — info */}
          <div style={{ padding: 32 }}>
            <div className="tracking-head" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, marginBottom: 24 }}>
              <div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 700, letterSpacing: "0.15em", textTransform: "uppercase" }}>
                  {lang === "fa" ? "سفارش" : "Order"} #{order.id}
                </div>
                <div className="display" style={{ fontSize: 28, marginTop: 4 }}>
                  {lang === "fa" ? `${toFa(remainingMin)} دقیقه تا تحویل` : `${remainingMin} min to go`}
                </div>
              </div>
              <div style={{
                background: accent, color: "#fff", padding: "10px 14px", borderRadius: 14,
                display: "flex", alignItems: "center", gap: 8, boxShadow: "0 4px 0 var(--brand-deep)"
              }}>
                <span style={{ width: 8, height: 8, borderRadius: 999, background: "#fff", animation: "pulse 1.4s infinite" }} />
                <span style={{ fontWeight: 800, fontSize: 13 }}>{lang === "fa" ? "زنده" : "LIVE"}</span>
              </div>
            </div>

            {/* live delivery route */}
            <div className="tracking-route-card" style={{
              marginBottom: 30, padding: "18px 18px 14px", borderRadius: 20,
              background: "var(--paper-2)", border: "1px solid var(--line)",
            }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginBottom: 18 }}>
                <div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 750 }}>
                    {lang === "fa" ? "وضعیت لحظه‌ای سفارش" : "Real-time order status"}
                  </div>
                  <div className="display" style={{ marginTop: 2, fontSize: 17 }}>{currentStep[lang]}</div>
                </div>
                <span className="tnum" style={{ fontSize: 20, fontWeight: 900, color: accent }}>
                  {lang === "fa" ? `${toFa(progressPercent)}٪` : `${progressPercent}%`}
                </span>
              </div>
              <div className="tracking-route" role="progressbar"
                aria-label={lang === "fa" ? "میزان پیشرفت سفارش" : "Order progress"}
                aria-valuemin="0" aria-valuemax="100" aria-valuenow={progressPercent}
                aria-valuetext={`${currentStep[lang]}، ${progressPercent}%`}
                style={{
                  "--track-progress": `${progressValue}%`,
                  position: "relative", height: 12, borderRadius: 999,
                  background: "rgba(26,20,16,.13)", border: "1.5px solid var(--ink)",
                  margin: "0 26px 12px",
                }}>
                <div className="tracking-fill" style={{
                  position: "absolute", insetBlock: 0, [lang === "fa" ? "right" : "left"]: 0,
                  width: "var(--track-progress)", borderRadius: 999,
                  background: `linear-gradient(${lang === "fa" ? "270deg" : "90deg"}, ${accent}, #E8B14A)`,
                }} />
                <div className="tracking-rider" aria-hidden="true" style={{
                  position: "absolute", zIndex: 2, top: "50%",
                  [lang === "fa" ? "right" : "left"]: "var(--track-progress)",
                  width: 44, height: 44, borderRadius: 15, display: "grid", placeItems: "center",
                  background: "var(--ink)", color: "var(--gold)", border: "3px solid var(--paper)",
                  boxShadow: "0 8px 18px rgba(26,20,16,.28)",
                  transform: lang === "fa" ? "translate(50%, -50%)" : "translate(-50%, -50%)",
                }}><span className="tracking-rider-motion" style={{ animationPlayState: progress < 1 ? "running" : "paused" }}><Ico.Scooter /></span></div>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 10, color: "var(--ink-3)", fontSize: 11, fontWeight: 700 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Ico.Store width="15" height="15" />{lang === "fa" ? "آشپزخانه" : "Kitchen"}</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>{lang === "fa" ? "مقصد شما" : "Your address"}<Ico.Home width="15" height="15" /></span>
              </div>
            </div>

            {/* steps */}
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              {steps.map((s, i) => {
                const done = i <= activeIdx;
                const active = i === activeIdx;
                return (
                  <div key={s.key} style={{
                    display: "flex", gap: 14, alignItems: "center",
                    opacity: done ? 1 : 0.4,
                  }}>
                    <div style={{
                      width: 40, height: 40, borderRadius: 999,
                      background: done ? "var(--ink)" : "var(--paper-2)",
                      color: done ? "var(--paper)" : "var(--ink-3)",
                      border: "1.5px solid var(--ink)",
                      display: "grid", placeItems: "center", fontSize: 18,
                      flexShrink: 0,
                      animation: active ? "stepPulse 2s ease-in-out infinite" : "none",
                    }}>{done && i < activeIdx ? <Ico.Check /> : s.ic}</div>
                    <div style={{ flex: 1 }}>
                      <div className="display" style={{ fontSize: 16 }}>{s[lang]}</div>
                      {active && <div style={{ fontSize: 12, color: accent, fontWeight: 600, marginTop: 2 }}>
                        {lang === "fa" ? "● همین الان" : "● happening now"}
                      </div>}
                    </div>
                  </div>
                );
              })}
            </div>

            {/* courier */}
            <div style={{
              marginTop: 28, padding: 16,
              background: "var(--paper-2)", borderRadius: 18, border: "1px solid var(--line)",
              display: "flex", alignItems: "center", gap: 14,
            }}>
              <div style={{ width: 52, height: 52, borderRadius: 999, background: accent, color: "#fff", display: "grid", placeItems: "center" }}><Ico.Scooter /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 700 }}>{lang === "fa" ? "پیک شما" : "Your rider"}</div>
                <div className="display" style={{ fontSize: 18, marginTop: 2 }}>{pick(order.courier, lang)}</div>
              </div>
              <a className="btn btn-dark btn-sm" href="tel:091234567890"><Ico.Phone /> {lang === "fa" ? "تماس" : "Call"}</a>
            </div>
          </div>

          {/* RIGHT — fake map */}
          <FakeMap accent={accent} progress={progress} />
        </div>
      </Wrap>
      <style>{`
        @keyframes pulse { 0%,100% { opacity:1; } 50% { opacity:0.4; } }
        @keyframes stepPulse { 0%,100% { transform:scale(1); box-shadow: 0 0 0 0 rgba(217,70,30,0.4); } 50% { transform:scale(1.06); box-shadow: 0 0 0 10px rgba(217,70,30,0); } }
        @keyframes trackingRiderMove {
          0%,100% { transform: rotate(-3deg); }
          50% { transform: rotate(3deg); }
        }
        @keyframes mapRiderMove {
          0%,100% { transform: rotate(-4deg); }
          50% { transform: rotate(4deg); }
        }
        .tracking-rider-motion {
          width: 100%; height: 100%; display: grid; place-items: center;
          animation: trackingRiderMove .9s ease-in-out infinite;
        }
        .map-rider-motion {
          transform-box: fill-box; transform-origin: center;
          animation: mapRiderMove 1s ease-in-out infinite;
        }
        @media (max-width: 560px) {
          .tracking-head { align-items: flex-start !important; }
          .tracking-route-card { padding-inline: 14px !important; }
        }
        @media (prefers-reduced-motion: reduce) {
          .tracking-fill, .tracking-rider, .map-rider { transition: none !important; }
          .tracking-rider-motion, .map-rider-motion { animation: none !important; }
        }
      `}</style>
    </section>
  );
}

function FakeMap({ accent, progress = 0.5 }) {
  const { lang } = useLang();
  const routeRef = React.useRef(null);
  const riderRef = React.useRef(null);
  const routeProgress = Math.max(0, Math.min(progress * 100, 100));
  const progressPercent = progress === 1 ? 100 : Math.min(99, Math.round(routeProgress));

  React.useLayoutEffect(() => {
    const path = routeRef.current;
    if (!path || !riderRef.current) return;

    const total = path.getTotalLength();
    const distance = total * (routeProgress / 100);
    const point = path.getPointAtLength(distance);
    riderRef.current.setAttribute("transform", `translate(${point.x} ${point.y})`);
  }, [routeProgress]);

  return (
    <div role="img" aria-label={lang === "fa" ? `نقشه مسیر سفارش، ${toFa(progressPercent)} درصد طی شده` : `Order route map, ${progressPercent} percent complete`} style={{ position: "relative", background: "#E8DFCF", minHeight: 460 }}>
      <svg aria-hidden="true" viewBox="0 0 500 500" style={{ width: "100%", height: "100%", display: "block" }}>
        <defs>
          <pattern id="grid" width="30" height="30" patternUnits="userSpaceOnUse">
            <path d="M0 30L30 30M30 0L30 30" stroke="rgba(26,20,16,0.08)" strokeWidth="1" fill="none"/>
          </pattern>
        </defs>
        <rect width="500" height="500" fill="url(#grid)"/>
        {/* random blocks (buildings) */}
        {[[40,60,80,60],[150,40,60,90],[260,80,90,50],[380,40,70,80],
          [50,200,100,80],[200,220,80,60],[320,210,90,70],
          [60,340,80,90],[180,340,120,60],[330,330,100,90]].map((b,i)=>(
          <rect key={i} x={b[0]} y={b[1]} width={b[2]} height={b[3]} fill="rgba(26,20,16,0.06)" rx="4"/>
        ))}
        {/* road path */}
        <path ref={routeRef} id="route" d="M80 420 Q 130 380 130 320 Q 130 260 200 240 Q 280 220 320 160 Q 360 100 420 80"
          fill="none" stroke="rgba(26,20,16,0.15)" strokeWidth="14" strokeLinecap="round"/>
        <path d="M80 420 Q 130 380 130 320 Q 130 260 200 240 Q 280 220 320 160 Q 360 100 420 80"
          fill="none" stroke={accent} strokeWidth="5" strokeLinecap="round"
          className="map-route-fill" pathLength="100" strokeDasharray={`${routeProgress} 100`}
          strokeDashoffset="0"/>
        {/* origin marker */}
        <g transform="translate(80 420)">
          <circle r="14" fill="var(--ink)"/>
          <Ico.Store x="-8" y="-8" width="16" height="16" style={{ color: "#fff" }} />
        </g>
        {/* destination marker */}
        <g transform="translate(420 80)">
          <circle r="14" fill={accent}/>
          <Ico.Home x="-8" y="-8" width="16" height="16" style={{ color: "#fff" }} />
        </g>
        {/* rider position follows actual order progress */}
        <g ref={riderRef} className="map-rider" transform="translate(80 420)">
          <circle r="21" fill="#fff" stroke={accent} strokeWidth="3"/>
          <g className="map-rider-motion" style={{ animationPlayState: progress < 1 ? "running" : "paused" }}>
            <Ico.Scooter x="-12" y="-12" width="24" height="24" style={{ color: accent }} />
          </g>
        </g>
      </svg>
      <div style={{
        position: "absolute", top: 16, insetInlineStart: 16,
        background: "var(--paper)", border: "1.5px solid var(--ink)", borderRadius: 14,
        padding: "10px 14px", fontSize: 12, fontWeight: 700,
      }}>{lang === "fa" ? `نقشه زنده · ${toFa(progressPercent)}٪ مسیر` : `Live map · ${progressPercent}% complete`}</div>
      <div style={{
        position: "absolute", bottom: 16, insetInlineEnd: 16,
        display: "flex", gap: 8, padding: "9px 12px",
        background: "rgba(255,244,226,.92)", border: "1px solid var(--line)",
        borderRadius: 12, fontSize: 11, fontWeight: 750, boxShadow: "var(--shadow-soft)",
      }}>
        <span>{lang === "fa" ? "مسیر تخمینی" : "Estimated route"}</span>
        <strong className="tnum">{lang === "fa" ? "۲٫۸ کیلومتر" : "2.8 km"}</strong>
      </div>
    </div>
  );
}

window.Tracking = Tracking;
