/* HudCo — Booking drawer: shell, browse, detail, cart steps */
const {
  Button: BK_Button, IconButton: BK_IconButton, Card: BK_Card,
  PriceTag: BK_PriceTag, Rating: BK_Rating, Alert: BK_Alert,
} = window.HudCoDesignSystem_e27b9b;
const { useState: BK_useState, useEffect: BK_useEffect, useLayoutEffect: BK_useLayoutEffect } = React;
const Ico = (n, p) => <i data-lucide={n} {...(p || {})}></i>;

/* ---- BrowseStep ---- */
function BrowseStep({ onSelect }) {
  return (
    <div className="bk-body">
      <p style={{ fontSize: 15, color: "var(--ink-600)", margin: 0 }}>Pick a service to see your flat price — parts included.</p>
      {(window.HUDCO_SERVICES || []).map(s => (
        <BK_Card key={s.id} padding="sm" interactive onClick={() => onSelect(s)}>
          <div className="ap-srow">
            <span className="ap-srow__ic">{Ico(s.icon)}</span>
            <div className="ap-srow__info"><b>{s.name}</b><span>{Ico("clock", { style: { width: 12, height: 12 } })} {s.time}</span></div>
            <BK_PriceTag amount={s.price} unit="flat" size="sm" />
          </div>
        </BK_Card>
      ))}
    </div>
  );
}

/* ---- DetailStep ---- */
function DetailStep({ svc, onAddToCart, addedToCart }) {
  return (
    <>
      <div className="bk-body">
        <div className="ap-hero">{Ico("image")}<span>{Ico("image")} Service photo placeholder</span></div>
        <div>
          <h2 className="ap-detail__title">{svc.name}</h2>
          <div className="ap-detail__meta"><BK_Rating value={4.9} size="sm" showValue /><span>· {svc.time}</span></div>
        </div>
        <p style={{ fontSize: 15, color: "var(--ink-600)", lineHeight: 1.55, margin: 0 }}>{svc.desc}</p>
        {svc.includes && svc.includes.length > 0 && (
          <BK_Card padding="md">
            <div className="ap-label" style={{ marginBottom: 12 }}>What's included</div>
            <ul className="ap-incl">
              {svc.includes.map(item => <li key={item}>{Ico("check-circle")}<span>{item}</span></li>)}
            </ul>
          </BK_Card>
        )}
        <BK_Alert tone="success" icon={Ico("lock")}>
          <b>${svc.price} flat</b> — parts included. You'll only ever pay this.
        </BK_Alert>
      </div>
      <div className="bk-dock">
        <div className="bk-dock__price"><small>Flat price</small><BK_PriceTag amount={svc.price} size="sm" /></div>
        <BK_Button variant={addedToCart ? "secondary" : "primary"} size="lg"
          iconRight={addedToCart ? Ico("check") : Ico("shopping-cart")}
          onClick={onAddToCart}>
          {addedToCart ? "Added to cart" : "Add to cart"}
        </BK_Button>
      </div>
    </>
  );
}

/* ---- CartStep ---- */
function CartStep({ cart, onUpdate, onRemove, onNext }) {
  const total = cart.reduce((s, i) => s + i.service.price * i.quantity, 0);
  const totalMins = cart.reduce((m, item, idx) => {
    const t = idx === 0 ? (item.service.baseTime || 60) : (item.service.additionalTime || 30);
    return m + t * item.quantity;
  }, 0);
  const h = Math.floor(totalMins / 60), mins = totalMins % 60;
  const timeEst = h > 0 ? `${h}h${mins > 0 ? ` ${mins}m` : ""}` : `${totalMins} min`;

  return (
    <>
      <div className="bk-body">
        {cart.length === 0 ? (
          <div style={{ textAlign: "center", padding: "48px 0", color: "var(--text-muted)" }}>
            <p style={{ margin: 0 }}>Your cart is empty.<br />Browse services below to add items.</p>
          </div>
        ) : cart.map(item => (
          <BK_Card key={item.service.id} padding="sm">
            <div className="ap-srow">
              <span className="ap-srow__ic">{Ico(item.service.icon)}</span>
              <div className="ap-srow__info"><b>{item.service.name}</b><span>{item.service.time}</span></div>
              <div className="bk-qty">
                <button className="bk-qty__btn" onClick={() => onUpdate(item.service.id, item.quantity - 1)}>−</button>
                <span className="bk-qty__n">{item.quantity}</span>
                <button className="bk-qty__btn" onClick={() => onUpdate(item.service.id, item.quantity + 1)}>+</button>
              </div>
            </div>
            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 8 }}>
              <BK_PriceTag amount={item.service.price * item.quantity} unit="flat" size="sm" />
            </div>
          </BK_Card>
        ))}
        {cart.length > 0 && (
          <div className="bk-cart-summary">
            <div className="bk-cart-summary__row"><span>Est. visit time</span><b>{timeEst}</b></div>
            {cart.length > 1 && <div className="bk-cart-summary__row"><span>Bundled visit</span><b style={{ color: "var(--success)" }}>1 trip out — saves time</b></div>}
          </div>
        )}
      </div>
      {cart.length > 0 && (
        <div className="bk-dock">
          <div className="bk-dock__price"><small>Total</small><BK_PriceTag amount={total} size="sm" /></div>
          <BK_Button variant="primary" size="lg" iconRight={Ico("arrow-right")} onClick={onNext}>Schedule visit</BK_Button>
        </div>
      )}
    </>
  );
}
window.CartStep = CartStep;

/* ---- BookingDrawer ---- */
const BK_STEP_TITLES = {
  browse: "Choose a service", detail: null, cart: "Your cart",
  schedule: "Pick a time", confirm: "Confirm & pay", success: "You're booked!",
};

function BookingDrawer({ open, mode, initialService, cart, onAddToCart, onUpdateCart, onRemoveCart, onClose }) {
  const [step, setStep] = BK_useState("browse");
  const [svc, setSvc] = BK_useState((window.HUDCO_SERVICES || [])[0]);
  const [day, setDay] = BK_useState(0);
  const [slot, setSlot] = BK_useState(null);
  const [photo, setPhoto] = BK_useState(null);
  const [addedToCart, setAddedToCart] = BK_useState(false);

  BK_useEffect(() => {
    if (open) {
      setDay(0); setSlot(null); setPhoto(null); setAddedToCart(false);
      if (mode === "cart") setStep("cart");
      else if (mode === "service" && initialService) { setSvc(initialService); setStep("detail"); }
      else setStep("browse");
    }
  }, [open, mode, initialService]);

  BK_useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  BK_useLayoutEffect(() => { if (window.lucide) window.lucide.createIcons(); });

  function handleAddToCart() {
    onAddToCart(svc);
    setAddedToCart(true);
    setTimeout(() => { setAddedToCart(false); onClose(); }, 1200);
  }

  const canGoBack = step === "detail" || step === "schedule" || step === "confirm";
  function handleBack() {
    if (step === "detail")   setStep("browse");
    if (step === "schedule") setStep("cart");
    if (step === "confirm")  setStep("schedule");
  }

  const dotMap = { cart: -1, browse: -1, detail: 0, schedule: 1, confirm: 2, success: 3 };
  const showProgress = step === "schedule" || step === "confirm";
  const title = step === "detail" ? (svc?.name || "") : (BK_STEP_TITLES[step] || "");

  /* Access flow steps from HudCoBookingFlow.jsx globals */
  const BK_ScheduleStep = window.ScheduleStep;
  const BK_ConfirmStep  = window.ConfirmStep;
  const BK_SuccessStep  = window.SuccessStep;

  return (
    <>
      <div className={"bk-backdrop" + (open ? " bk-backdrop--open" : "")} onClick={onClose}></div>
      <div className={"bk-drawer" + (open ? " bk-drawer--open" : "")}>
        <div className="bk-header">
          {canGoBack
            ? <button className="bk-icon-btn" onClick={handleBack} aria-label="Back">{Ico("arrow-left")}</button>
            : <div className="bk-placeholder"></div>}
          <h2 className="bk-title">{title}</h2>
          <button className="bk-icon-btn" onClick={onClose} aria-label="Close">{Ico("x")}</button>
        </div>
        {showProgress && (
          <div className="bk-progress">
            {[1, 2, 3].map(i => (
              <div key={i} className={"bk-pdot" + (i < dotMap[step] ? " bk-pdot--done" : i === dotMap[step] ? " bk-pdot--active" : "")}></div>
            ))}
          </div>
        )}
        {step === "browse"   && <BrowseStep onSelect={s => { setSvc(s); setStep("detail"); }} />}
        {step === "detail"   && <DetailStep svc={svc} onAddToCart={handleAddToCart} addedToCart={addedToCart} />}
        {step === "cart"     && <CartStep cart={cart} onUpdate={onUpdateCart} onRemove={onRemoveCart} onNext={() => setStep("schedule")} />}
        {step === "schedule" && BK_ScheduleStep && <BK_ScheduleStep cart={cart} day={day} setDay={setDay} slot={slot} setSlot={setSlot} photo={photo} setPhoto={setPhoto} onNext={() => setStep("confirm")} />}
        {step === "confirm"  && BK_ConfirmStep  && <BK_ConfirmStep  cart={cart} day={day} slot={slot} photo={photo} onNext={() => setStep("success")} />}
        {step === "success"  && BK_SuccessStep  && <BK_SuccessStep  cart={cart} day={day} slot={slot} onClose={onClose} />}
      </div>
    </>
  );
}
window.BookingDrawer = BookingDrawer;
