/* ============================================================================
   PLACES — Sights checklist + Food guide. One-tap Maps on everything.
   ============================================================================ */
function PlacesScreen({ state, actions }) {
  const T = window.TRIP;
  const [sub, setSub] = React.useState("sights");

  return (
    <div style={{ padding: "8px 16px 8px" }}>
      <SegTabs
        value={sub}
        onChange={setSub}
        tabs={[
          { id: "sights", label: "Sights", icon: "location" },
          { id: "food", label: "Food", icon: "food" },
        ]}
      />
      {sub === "sights" ? <Sights state={state} actions={actions} /> : <Food state={state} actions={actions} />}
    </div>
  );
}

const TIME_STYLE = {
  Morning:   { bg: "rgba(234,163,0,0.16)",  fg: "#9a6a00" },
  Afternoon: { bg: "rgba(3,131,135,0.14)",  fg: "var(--color-darkTeal)" },
  Evening:   { bg: "rgba(113,96,232,0.16)", fg: "var(--color-lavender)" },
  Night:     { bg: "rgba(0,79,120,0.16)",   fg: "var(--color-blue)" },
};
function timeChipStyle(t) {
  const c = TIME_STYLE[t] || { bg: "var(--colorNeutralBackground3)", fg: "var(--colorNeutralForeground3)" };
  return { display: "inline-block", padding: "2px 9px", borderRadius: 999, fontSize: 11, fontWeight: 700,
    background: c.bg, color: c.fg, fontFamily: "var(--fontFamilyBase)" };
}

function Sights({ state, actions }) {
  const T = window.TRIP;
  const cityName = (T.cities[0] && T.cities[0].name) || "Hanoi";
  const seen = state.places.filter((p) => p.visited).length;
  const { pos, denied, available, fetching, refresh } = window.geo.useGeo();

  // group by itinerary day, preserving the order they appear in the data
  const days = [];
  state.places.forEach((p) => { const d = p.day || cityName; if (!days.includes(d)) days.push(d); });

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ fontSize: 13, color: "var(--colorNeutralForeground3)", fontWeight: 600 }}>
          {seen}/{state.places.length} ticked off
        </div>
        <Chip tone="teal"><Icon name="checkmark_circle" size={13} filled color="var(--color-teal)" /> Tap a circle to check in</Chip>
      </div>

      {available && (
        <div style={{ fontSize: 12, color: "var(--colorNeutralForeground3)", margin: "-6px 2px 0", display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
          <Icon name="location" size={13} color="var(--color-teal)" />
          {denied
            ? <span>Location is off — enable it for the browser to see distances.</span>
            : !pos
              ? <span>{fetching ? "Finding your location…" : "Allow location to see how far each spot is."}</span>
              : <span>Distances from your location · <button onClick={refresh} style={{ border: "none", background: "none", padding: 0, color: "var(--color-teal)", fontWeight: 700, cursor: "pointer", fontSize: 12, fontFamily: "var(--fontFamilyBase)" }}>{fetching ? "updating…" : "update"}</button></span>}
        </div>
      )}

      {days.map((day) => {
        const items = state.places.filter((p) => (p.day || cityName) === day);
        const done = items.filter((p) => p.visited).length;
        return (
          <div key={day}>
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", margin: "0 2px 8px" }}>
              <Serif size={19} weight={600}>{day}</Serif>
              <span style={{ fontSize: 12, fontWeight: 700, color: done === items.length && items.length ? "var(--color-teal)" : "var(--colorNeutralForeground3)" }}>{done}/{items.length}</span>
            </div>
            <Card pad={0}>
              {items.map((p, i) => (
                <PlaceRow key={p.id} place={p} cityName={cityName} last={i === items.length - 1}
                  distance={pos ? window.geo.fmt(window.geo.distanceTo(p.lat, p.lng)) : null}
                  onToggle={() => actions.togglePlace(p.id)} />
              ))}
            </Card>
          </div>
        );
      })}
    </div>
  );
}

function PlaceRow({ place, cityName, last, onToggle, distance }) {
  return (
    <div style={{
      display: "flex", alignItems: "flex-start", gap: 12, padding: "13px 14px",
      borderBottom: last ? "none" : "1px solid var(--colorNeutralStroke3)",
    }}>
      <button onClick={onToggle} aria-label="toggle visited" style={{
        marginTop: 1, width: 26, height: 26, borderRadius: "50%", flexShrink: 0, cursor: "pointer",
        border: place.visited ? "none" : "2px solid var(--colorNeutralStroke1)",
        background: place.visited ? "var(--color-teal)" : "transparent",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        transition: "all var(--durationFast) var(--curveEasyEase)",
      }}>
        {place.visited && <Icon name="checkmark" size={16} color="#fff" />}
      </button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 14.5, fontWeight: 600, lineHeight: 1.3,
          color: place.visited ? "var(--colorNeutralForeground3)" : "var(--colorNeutralForeground1)",
        }}>
          <span style={{ textDecoration: place.visited ? "line-through" : "none", textDecorationColor: "var(--colorNeutralForeground4)" }}>{place.name}</span>
          {place.fav && <Icon name="heart" size={14} filled color="var(--color-pumpkin)" style={{ marginLeft: 6 }} />}
        </div>
        <div style={{ fontSize: 12.5, color: "var(--colorNeutralForeground3)", marginTop: 3, lineHeight: 1.3 }}>{place.note}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8, flexWrap: "wrap" }}>
          {place.time && <span style={timeChipStyle(place.time)}>{place.time}</span>}
          {distance && <span style={{ display: "inline-flex", alignItems: "center", gap: 3, fontSize: 11.5, fontWeight: 700, color: "var(--color-darkTeal)" }}><Icon name="location" size={12} filled color="var(--color-teal)" />{distance}</span>}
          <Chip tone="neutral">{place.type}</Chip>
          <MapsLink query={`${place.name} ${cityName}`} lat={place.lat} lng={place.lng} label="Navigate" />
        </div>
      </div>
    </div>
  );
}

function Food({ state, actions }) {
  const T = window.TRIP;
  const tried = state.dishes.filter((d) => d.tried).length;
  const { pos } = window.geo.useGeo();
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      {/* dishes to try */}
      <div>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", margin: "0 2px 10px" }}>
          <Serif size={20} weight={600}>Dishes to try</Serif>
          <span style={{ fontSize: 12, fontWeight: 700, color: "var(--color-brass)" }}>{tried}/{state.dishes.length} tasted</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 9 }}>
          {state.dishes.map((d) => (
            <button key={d.id} onClick={() => actions.toggleDish(d.id)} style={{
              textAlign: "left", cursor: "pointer", fontFamily: "var(--fontFamilyBase)",
              padding: "11px 12px", borderRadius: 14,
              border: d.tried ? "1px solid rgba(234,163,0,0.5)" : "1px solid var(--colorNeutralStroke2)",
              background: d.tried ? "rgba(234,163,0,0.10)" : "var(--colorNeutralBackground1)",
              display: "flex", alignItems: "flex-start", gap: 9, boxShadow: "var(--shadow2)",
            }}>
              <span style={{
                width: 22, height: 22, borderRadius: "50%", flexShrink: 0, marginTop: 1,
                border: d.tried ? "none" : "2px solid var(--colorNeutralStroke1)",
                background: d.tried ? "var(--color-marigold)" : "transparent",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
              }}>{d.tried && <Icon name="checkmark" size={13} color="#3a2c00" />}</span>
              <span>
                <span style={{ display: "block", fontSize: 13.5, fontWeight: 700, color: "var(--colorNeutralForeground1)" }}>{d.name}</span>
                <span style={{ display: "block", fontSize: 11.5, color: "var(--colorNeutralForeground3)", marginTop: 1, lineHeight: 1.3 }}>{d.sub}</span>
              </span>
            </button>
          ))}
        </div>
      </div>

      {/* restaurants */}
      <div>
        <div style={{ margin: "0 2px 10px" }}>
          <Serif size={20} weight={600}>Where to eat</Serif>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {state.restaurants.map((r) => {
            const city = T.cities.find((c) => c.id === r.city);
            const dist = pos ? window.geo.fmt(window.geo.distanceTo(r.lat, r.lng)) : null;
            return (
              <Card key={r.id} pad={14}>
                <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                  <span style={{ width: 44, height: 44, borderRadius: 12, flexShrink: 0,
                    background: "rgba(202,80,16,0.10)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                    <Icon name="bowl_chopsticks" size={22} color="var(--color-pumpkin)" />
                  </span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                      <span style={{ fontSize: 15, fontWeight: 700, color: "var(--colorNeutralForeground1)" }}>{r.name}</span>
                      <button onClick={() => actions.toggleBookmark(r.id)} aria-label="bookmark" style={{ border: "none", background: "none", cursor: "pointer", padding: 2 }}>
                        <Icon name="bookmark" size={19} filled={r.bookmarked} color={r.bookmarked ? "var(--color-pumpkin)" : "var(--colorNeutralForeground4)"} />
                      </button>
                    </div>
                    <div style={{ fontSize: 12.5, color: "var(--colorNeutralForeground3)", marginTop: 2 }}>{r.note}</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 9, flexWrap: "wrap" }}>
                      <Chip tone="pumpkin">{r.dish}</Chip>
                      <span style={{ fontSize: 12, color: "var(--colorNeutralForeground4)", fontWeight: 700 }}>{r.price}</span>
                      {dist && <span style={{ display: "inline-flex", alignItems: "center", gap: 3, fontSize: 11.5, fontWeight: 700, color: "var(--color-darkTeal)" }}><Icon name="location" size={12} filled color="var(--color-teal)" />{dist}</span>}
                      <span style={{ marginLeft: "auto" }}><MapsLink query={`${r.name} ${city.name}`} lat={r.lat} lng={r.lng} label="Navigate" /></span>
                    </div>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PlacesScreen });
