// preview.jsx — live calendar preview + summary card

function CalendarPreview({ data, justAdded }) {
  // pick day/time mapping
  const startH = 8, endH = 18; // 8am — 6pm
  const totalMin = (endH - startH) * 60;
  const heightPx = 280;
  const minToY = (m) => (m / totalMin) * heightPx;

  // build the 3-day window centered on the selected date
  const sel = data.date ? new Date(data.date + "T00:00") : new Date();
  const days = [-1, 0, 1].map(off => {
    const d = new Date(sel);
    d.setDate(sel.getDate() + off);
    return d;
  });
  const today = new Date(); today.setHours(0,0,0,0);

  const evColor = (EVENT_COLORS.find(c => c.id === data.color) || EVENT_COLORS[0]).val;

  const eventTopMin = data.time
    ? (parseInt(data.time.split(":")[0],10) - startH) * 60 + parseInt(data.time.split(":")[1],10)
    : 9 * 60;
  const evTop = Math.max(0, Math.min(totalMin, eventTopMin));
  const evH   = Math.max(28, Math.min(totalMin - evTop, data.duration));

  const calMeta = CALENDARS.find(c => c.id === data.calendar) || CALENDARS[0];
  const colorTint = evColor + "22";
  const colorDeep = evColor;

  // a couple of static "neighbor" events to make the calendar feel real
  const ghostEvents = [
    { dayIdx: 0, top: 60,  h: 60,  title: "Sandwich audit",  who: "S. Rivera",   color: "#3B82C4" },
    { dayIdx: 0, top: 230, h: 45,  title: "Crew debrief",    who: "Office",      color: "#9C6BB0" },
    { dayIdx: 2, top: 120, h: 90,  title: "Insulation —  Lacroix", who: "Crew B", color: "#5E6F4F" },
  ];

  const title = data.name
    ? (data.jobType ? `${jobTypeLabel(data.jobType)} — ${data.name}` : `WX — ${data.name}`)
    : "New customer event";

  return (
    <div className="cal-card">
      <div className="cal-head">
        <div className="left">
          <span className="glogo"></span>
          <b>Google Calendar</b>
          <span style={{ fontSize: 12, color: "var(--ink-mute)", marginLeft: 4 }}>
            · {calMeta.label}
          </span>
        </div>
        <div className="right">
          {data.date ? sel.toLocaleDateString(undefined, { month: "long", year: "numeric" }) : "—"}
        </div>
      </div>

      {/* day header */}
      <div className="cal-grid">
        <div></div>
        {days.map((d, i) => {
          const isSel = i === 1 && data.date;
          const isToday = d.toDateString() === today.toDateString();
          return (
            <div key={i} className={"cal-day " + ((isSel || isToday) ? "is-today" : "")}>
              <div>{d.toLocaleDateString(undefined, { weekday: "short" })}</div>
              <div className="num" style={isSel ? { background: colorDeep } : null}>
                {d.getDate()}
              </div>
            </div>
          );
        })}
      </div>

      {/* body */}
      <div className="cal-body" style={{ height: heightPx }}>
        {/* time labels + lines */}
        <div className="cal-times">
          {Array.from({ length: endH - startH + 1 }, (_, i) => i + startH).map(h => (
            <span key={h} className="cal-time" style={{ "--y": `${minToY((h-startH)*60)}px` }}>
              {h % 12 === 0 ? 12 : h % 12}{h < 12 ? " AM" : " PM"}
            </span>
          ))}
        </div>

        {/* hour lines (across all columns) */}
        {Array.from({ length: endH - startH + 1 }, (_, i) => i).map(i => (
          <div key={"l"+i} className="cal-line" style={{ "--y": `${minToY(i*60)}px` }}></div>
        ))}

        {[0,1,2].map(i => (
          <div key={i} className="cal-col">
            {/* ghost events */}
            {ghostEvents.filter(g => g.dayIdx === i).map((g, idx) => (
              <div key={idx} className="cal-event"
                style={{
                  "--top": `${minToY(g.top)}px`,
                  "--h":   `${minToY(g.h)}px`,
                  "--ev":  g.color,
                  "--ev-bg": g.color + "1f",
                  "--ev-deep": g.color,
                  opacity: i === 1 ? 0.55 : 0.7,
                }}>
                <b>{g.title}</b>
                <div className="ev-time">{g.who}</div>
              </div>
            ))}

            {/* the new (live) event in the center column */}
            {i === 1 && data.date && data.time && (
              <div
                className={"cal-event " + (justAdded ? "is-new" : "")}
                style={{
                  "--top": `${minToY(evTop)}px`,
                  "--h":   `${minToY(evH)}px`,
                  "--ev":  colorDeep,
                  "--ev-bg": colorTint,
                  "--ev-deep": colorDeep,
                }}>
                <b>{title}</b>
                <div className="ev-time">
                  {fmtTime(data.time)} – {fmtTime(endTime(data.time, data.duration))}
                  {data.address ? ` · ${data.address.split(",")[0]}` : ""}
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

function jobTypeLabel(id) {
  return ({
    "waiting":    "Waiting to schedule",
    "scheduled":  "Scheduled",
    "callback":   "Call back",
    "roadblock":  "Road block pending",
    "reschedule": "Reschedule",
    "canceled":   "Canceled",
    "walk":       "WALK",
    "completed":  "Completed",
    "invoiced":   "Invoiced",
    "paid":       "Paid from vendor",
  })[id] || "WX";
}

function SummaryCard({ data }) {
  const fuel = FUEL_TYPES.find(f => f.id === data.fuel);
  const cal = CALENDARS.find(c => c.id === data.calendar) || CALENDARS[0];
  return (
    <div className="summary">
      <h3>At a glance</h3>
      <div className="row-pair">
        <span className="k">Customer</span>
        <span className={"v " + (data.name ? "" : "empty")}>
          {data.name || "—"}
        </span>
      </div>
      <div className="row-pair">
        <span className="k">When</span>
        <span className={"v " + (data.date && data.time ? "" : "empty")}>
          {data.date && data.time
            ? `${fmtDateLong(data.date)} · ${fmtTime(data.time)}`
            : "Pick a date & time"}
        </span>
      </div>
      <div className="row-pair">
        <span className="k">Duration</span>
        <span className="v">{durationLabel(data.duration)}</span>
      </div>
      <div className="row-pair">
        <span className="k">Where</span>
        <span className={"v " + (data.address ? "" : "empty")}>
          {data.address || "No address"}
        </span>
      </div>
      <div className="row-pair">
        <span className="k">Fuel</span>
        <span className={"v " + (fuel ? "" : "empty")}>
          {fuel ? fuel.label : "—"}
        </span>
      </div>
      <div className="row-pair">
        <span className="k">Contract</span>
        <span className={"v mono " + (data.amount ? "" : "empty")}>
          {data.amount ? `$${data.amount}` : "—"}
        </span>
      </div>
      <div className="row-pair">
        <span className="k">Calendar</span>
        <span className="v">{cal.label}</span>
      </div>
      <div className="row-pair">
        <span className="k">Status</span>
        <span className="v" style={{
          color: data.roadblock === "blocked" ? "var(--warn)" :
                 data.roadblock === "minor"   ? "var(--amber)" : "var(--accent)",
        }}>
          {data.roadblock === "blocked" ? "🚧 Blocked" :
           data.roadblock === "minor"   ? "⚠ Note for crew" :
           data.roadblock === "cleared" ? "✓ Cleared" :
           data.roadblock === "not-cleared" ? "⚠ Not cleared" : "✓ No road blocks"}
        </span>
      </div>
    </div>
  );
}

Object.assign(window, { CalendarPreview, SummaryCard, jobTypeLabel });
