import type { Trip, Weather, HourlyWeather } from "../../lib/types";

function tempColor(temp: number): string {
  if (temp >= 30) return "var(--error)";
  if (temp >= 25) return "var(--warning)";
  if (temp >= 18) return "var(--success)";
  if (temp >= 12) return "var(--info)";
  return "var(--info-light)";
}

function HourRow({ h }: { h: HourlyWeather }) {
  const color = tempColor(h.temp);
  return (
    <div class="wx-stop">
      <div class="wx-stop-left">
        <div class="wx-stop-time">{h.time}</div>
        <div class="wx-stop-temp" style={{ color }}>{h.temp}°</div>
        {h.feelsLike != null && h.feelsLike !== h.temp && (
          <div class="wx-stop-feels" style={{ color }}>feels {h.feelsLike}°</div>
        )}
      </div>
      <div class="wx-stop-right">
        <div class="wx-stop-location">{h.location}</div>
        <div class="wx-stop-cond">{h.conditions}{h.wind ? ` · ${h.wind}` : ""}</div>
        {h.note && <div class="wx-stop-note">{h.note}</div>}
      </div>
    </div>
  );
}

function DayWeather({ wx, dayLabel }: { wx: Weather; dayLabel: string }) {
  const dateStr = new Date(wx.date + "T12:00:00").toLocaleDateString("en-US", {
    weekday: "short", month: "short", day: "numeric",
  });

  return (
    <div class="wx-day-section">
      <div class="wx-day-header">
        <div class="wx-day-title">{dayLabel}</div>
        <div class="wx-day-date">{dateStr}</div>
      </div>

      <div class="wx-day-card">
        <div class="wx-day-overview">
          <div class="wx-day-temps">
            <span class="wx-hi">{wx.high}°</span>
            <span class="wx-sep">/</span>
            <span class="wx-lo">{wx.low}°</span>
          </div>
          <div class="wx-day-info">
            <div class="wx-day-cond">{wx.conditions}</div>
            <div class="wx-day-sun">Sunrise {wx.sunrise} · Sunset {wx.sunset}</div>
          </div>
        </div>

        {wx.hourly && wx.hourly.length > 0 && (
          <div class="wx-timeline">
            {wx.hourly.map((h, i) => (
              <HourRow key={i} h={h} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

export function WeatherTab({ trip }: { trip: Trip }) {
  return (
    <div class="weather-tab">
      <div class="food-tab-header">
        <div class="itin-section-label">Weather Along the Route</div>
      </div>

      {trip.weather.map((wx, i) => (
        <DayWeather
          key={wx.date}
          wx={wx}
          dayLabel={trip.days[i]?.label ?? `Day ${i + 1}`}
        />
      ))}
    </div>
  );
}
