/* ============================================================
   HOCHZEITSPLANER — Karte (Australien + Neuseeland)
   Zwei getrennte Panels mit eigenen Bounding-Boxen
   ============================================================ */

const TRIP_CITIES = {
  Sydney:           { lat: -33.87, lon: 151.21, country: "AU", label: "Sydney" },
  "Blue Mountains": { lat: -33.72, lon: 150.31, country: "AU", label: "Blue Mtns", sub: true },
  "Port Stephens":  { lat: -32.71, lon: 152.16, country: "AU", label: "Port Stephens" },
  "Coffs Harbour":  { lat: -30.30, lon: 153.12, country: "AU", label: "Coffs Harbour" },
  "Byron Bay":      { lat: -28.64, lon: 153.61, country: "AU", label: "Byron Bay" },
  Brisbane:         { lat: -27.47, lon: 153.03, country: "AU", label: "Brisbane", sub: true },
  Cairns:           { lat: -16.92, lon: 145.78, country: "AU", label: "Cairns", sub: true },
  "Port Douglas":   { lat: -16.48, lon: 145.46, country: "AU", label: "Port Douglas" },

  Auckland:         { lat: -36.85, lon: 174.76, country: "NZ", label: "Auckland" },
  Rotorua:          { lat: -38.14, lon: 176.25, country: "NZ", label: "Rotorua" },
  "Tongariro":      { lat: -39.13, lon: 175.65, country: "NZ", label: "Tongariro" },
  Wellington:       { lat: -41.29, lon: 174.78, country: "NZ", label: "Wellington" },
  Picton:           { lat: -41.29, lon: 174.00, country: "NZ", label: "Picton", sub: true },
  "Franz Josef":    { lat: -43.39, lon: 170.18, country: "NZ", label: "Franz Josef" },
  Wanaka:           { lat: -44.70, lon: 169.13, country: "NZ", label: "Wanaka" },
  "Mount Cook":     { lat: -43.74, lon: 170.10, country: "NZ", label: "Mt Cook" },
  "Te Anau":        { lat: -45.41, lon: 167.72, country: "NZ", label: "Te Anau" },
  "Milford Sound":  { lat: -44.67, lon: 167.93, country: "NZ", label: "Milford", sub: true },
  Queenstown:       { lat: -45.03, lon: 168.66, country: "NZ", label: "Queenstown" },
};

// Reise-Segmente — getrennt nach Panel (AU intern, NZ intern, AU↔NZ Transit)
const SEGMENTS_AU = [
  { from: "Sydney",          to: "Blue Mountains", mode: "drive", dotted: true },
  { from: "Sydney",          to: "Port Stephens",  mode: "drive" },
  { from: "Port Stephens",   to: "Coffs Harbour",  mode: "drive" },
  { from: "Coffs Harbour",   to: "Byron Bay",      mode: "drive" },
  { from: "Byron Bay",       to: "Brisbane",       mode: "drive" },
  { from: "Brisbane",        to: "Cairns",         mode: "flight" },
  { from: "Cairns",          to: "Port Douglas",   mode: "drive" },
];

const SEGMENTS_NZ = [
  { from: "Auckland",        to: "Rotorua",        mode: "drive" },
  { from: "Rotorua",         to: "Tongariro",      mode: "drive" },
  { from: "Tongariro",       to: "Wellington",     mode: "drive" },
  { from: "Wellington",      to: "Picton",         mode: "ferry" },
  { from: "Picton",          to: "Franz Josef",    mode: "drive" },
  { from: "Franz Josef",     to: "Wanaka",         mode: "drive" },
  { from: "Wanaka",          to: "Mount Cook",     mode: "drive" },
  { from: "Mount Cook",      to: "Te Anau",        mode: "drive" },
  { from: "Te Anau",         to: "Milford Sound",  mode: "drive", dotted: true },
  { from: "Te Anau",         to: "Queenstown",     mode: "drive" },
  { from: "Queenstown",      to: "Auckland",       mode: "flight" },
];

// Australien-Outline (vereinfacht)
const AUS_OUTLINE = [
  [142.5, -10.7], [144.5, -13.5], [145.5, -16.0], [146.5, -19.0],
  [149.0, -21.5], [150.5, -24.0], [152.5, -25.5], [153.3, -28.2],
  [153.6, -30.0], [153.6, -32.0], [151.5, -33.5], [150.5, -35.5],
  [149.5, -37.5], [147.5, -38.4], [146.0, -39.0], [143.5, -38.8],
  [141.0, -38.4], [140.5, -36.0], [139.5, -34.0], [138.5, -34.5],
  [136.5, -34.8], [134.0, -32.5], [131.5, -31.5], [130.0, -31.7],
  [126.0, -31.9], [122.0, -33.5], [118.0, -34.8], [115.5, -34.5],
  [114.7, -32.0], [114.5, -28.0], [114.0, -22.0], [116.0, -20.5],
  [120.0, -19.5], [122.5, -18.0], [125.5, -16.0], [128.5, -14.5],
  [130.5, -12.5], [132.5, -12.0], [135.0, -12.0], [137.0, -10.5],
  [139.0, -10.5], [141.5, -10.7], [142.5, -10.7],
];

// NZ Nordinsel — etwas detaillierter
const NZ_NORTH = [
  [172.7, -34.4], [173.3, -34.6], [174.0, -35.0], [174.5, -35.3],
  [174.8, -35.8], [175.2, -36.2], [175.5, -36.7], [176.0, -37.1],
  [176.5, -37.4], [177.0, -37.6], [177.5, -37.7], [178.0, -37.6],
  [178.4, -38.0], [178.5, -38.6], [178.0, -39.2], [177.4, -39.4],
  [176.9, -39.5], [176.5, -39.8], [176.5, -40.3], [176.6, -40.8],
  [176.2, -41.2], [175.5, -41.6], [175.0, -41.5], [174.7, -41.3],
  [174.4, -40.9], [174.5, -40.3], [174.0, -39.7], [173.4, -39.2],
  [172.9, -38.8], [172.7, -38.2], [173.0, -37.5], [173.4, -36.8],
  [173.0, -36.0], [172.8, -35.3], [172.7, -34.4],
];

// NZ Südinsel — detaillierter, kein direkter Schnitt mit Nordinsel
const NZ_SOUTH = [
  [172.5, -40.7], [173.2, -40.8], [174.0, -41.2], [174.2, -41.6],
  [173.8, -42.0], [173.5, -42.4], [173.0, -42.7], [172.8, -43.1],
  [172.5, -43.5], [172.3, -43.9], [171.8, -44.2], [171.5, -44.5],
  [171.0, -44.8], [170.7, -45.2], [170.5, -45.6], [170.3, -46.0],
  [169.8, -46.5], [169.0, -46.7], [168.0, -46.8], [167.0, -46.5],
  [166.5, -46.0], [166.3, -45.5], [166.5, -45.0], [167.0, -44.5],
  [167.5, -44.0], [168.0, -43.5], [167.8, -43.0], [168.2, -42.5],
  [169.0, -42.0], [169.8, -41.5], [170.8, -41.2], [171.7, -41.0],
  [172.5, -40.7],
];

// =============================================================
//  Helper: project lat/lon → SVG coords given bounding box
// =============================================================
function makeProjector(W, H, lonMin, lonMax, latMin, latMax, padding = 30) {
  return (lon, lat) => {
    const x = padding + ((lon - lonMin) / (lonMax - lonMin)) * (W - 2 * padding);
    const y = padding + ((latMax - lat) / (latMax - latMin)) * (H - 2 * padding);
    return [x, y];
  };
}

function buildPolyPath(pts, project) {
  return "M " + pts.map(([lon, lat]) => project(lon, lat).map(n => n.toFixed(1)).join(",")).join(" L ") + " Z";
}

// Build a path/curve for a route segment
function buildSegmentPath(s, project) {
  const a = TRIP_CITIES[s.from], b = TRIP_CITIES[s.to];
  const [x1, y1] = project(a.lon, a.lat);
  const [x2, y2] = project(b.lon, b.lat);
  if (s.mode === "flight") {
    const dist = Math.hypot(x2 - x1, y2 - y1);
    const curve = dist * 0.22;
    const mx = (x1 + x2) / 2;
    const my = (y1 + y2) / 2;
    const dx = x2 - x1, dy = y2 - y1;
    const nlen = Math.hypot(dx, dy) || 1;
    const nx = -dy / nlen, ny = dx / nlen;
    // bias arc outward away from coast
    const cx = mx + nx * curve;
    const cy = my + ny * curve;
    return `M ${x1.toFixed(1)} ${y1.toFixed(1)} Q ${cx.toFixed(1)} ${cy.toFixed(1)} ${x2.toFixed(1)} ${y2.toFixed(1)}`;
  }
  return `M ${x1.toFixed(1)} ${y1.toFixed(1)} L ${x2.toFixed(1)} ${y2.toFixed(1)}`;
}

// =============================================================
//  MapPanel — generic panel for one country
// =============================================================
function MapPanel({
  title, eyebrow, days, kmTotal,
  outlines, // [{pts: [[lon,lat],...], label?}]
  segments,
  cityKeys,
  bbox, // { lonMin, lonMax, latMin, latMax }
  width = 580, height = 640,
  countryLabel,
  countryLabelPos, // [lon, lat]
  startKey,
  hashLabels = {},
}) {
  const project = makeProjector(width, height, bbox.lonMin, bbox.lonMax, bbox.latMin, bbox.latMax, 40);

  const cities = cityKeys.map(k => {
    const c = TRIP_CITIES[k];
    const [x, y] = project(c.lon, c.lat);
    return { ...c, key: k, x, y };
  });

  return (
    <div style={{
      flex: 1,
      background: "var(--paper)",
      border: "1px solid var(--rule)",
      padding: 20,
      display: "flex",
      flexDirection: "column",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 12 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 4 }}>{eyebrow}</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 28, lineHeight: 1 }}>{title}</div>
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-mute)", textAlign: "right", lineHeight: 1.5 }}>
          {days} Tage<br/>{kmTotal > 0 ? `${kmTotal.toLocaleString("de-DE")} km` : ""}
        </div>
      </div>
      <svg viewBox={`0 0 ${width} ${height}`} style={{ width: "100%", height: "auto", display: "block", flex: 1 }}>
        {/* Subtle grid */}
        <defs>
          <pattern id={`grid-${eyebrow}`} width="40" height="40" patternUnits="userSpaceOnUse">
            <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#ece2ce" strokeWidth="0.3" />
          </pattern>
        </defs>
        <rect width={width} height={height} fill="#fbf6ec" />
        <rect width={width} height={height} fill={`url(#grid-${eyebrow})`} opacity="0.5" />

        {/* Landmasses */}
        {outlines.map((o, i) => (
          <path key={i} d={buildPolyPath(o.pts, project)} fill="#ece2ce" stroke="#d4c3a0" strokeWidth="1" />
        ))}

        {/* Country label (background) */}
        {countryLabel && (
          <text
            x={project(countryLabelPos[0], countryLabelPos[1])[0]}
            y={project(countryLabelPos[0], countryLabelPos[1])[1]}
            fontFamily="var(--font-display)"
            fontSize="48"
            fill="#d4c3a0"
            fontStyle="italic"
            textAnchor="middle"
            opacity="0.7"
          >
            {countryLabel}
          </text>
        )}

        {/* Route segments */}
        {segments.map((s, i) => {
          const stroke = s.mode === "flight" ? "var(--gold)" : s.mode === "ferry" ? "var(--sage)" : "var(--wine)";
          const dasharray = s.dotted ? "2 4" : s.mode === "flight" ? "6 5" : s.mode === "ferry" ? "1 4" : "none";
          return (
            <path
              key={i}
              d={buildSegmentPath(s, project)}
              fill="none"
              stroke={stroke}
              strokeWidth={s.dotted ? 1.2 : 2.2}
              strokeDasharray={dasharray}
              strokeLinecap="round"
              opacity={s.dotted ? 0.55 : 0.9}
            />
          );
        })}

        {/* City dots */}
        {cities.map(c => (
          <g key={c.key}>
            {!c.sub && (
              <circle cx={c.x} cy={c.y} r="8" fill="var(--wine)" opacity="0.15" />
            )}
            <circle
              cx={c.x} cy={c.y}
              r={c.sub ? 3 : 4.5}
              fill={c.sub ? "var(--paper)" : "var(--wine)"}
              stroke="var(--wine)"
              strokeWidth={c.sub ? 1.2 : 1.5}
            />
          </g>
        ))}

        {/* City labels — uses hashLabels for per-city offsets */}
        {cities.map(c => {
          const o = hashLabels[c.key] || { dx: 9, dy: 4 };
          return (
            <text
              key={c.key}
              x={c.x + o.dx}
              y={c.y + o.dy}
              fontFamily="var(--font-body)"
              fontSize={c.sub ? 10 : 13}
              fontWeight={c.sub ? 400 : 500}
              fill={c.sub ? "var(--ink-mute)" : "var(--ink)"}
              textAnchor={o.anchor || "start"}
              fontStyle={c.sub ? "italic" : "normal"}
              style={{ paintOrder: "stroke", stroke: "#fbf6ec", strokeWidth: 3, strokeLinejoin: "round" }}
            >
              {c.label}
            </text>
          );
        })}

        {/* START tag */}
        {startKey && (() => {
          const c = TRIP_CITIES[startKey];
          const [x, y] = project(c.lon, c.lat);
          return (
            <g transform={`translate(${x - 22}, ${y - 22})`}>
              <rect x="0" y="0" width="44" height="14" fill="var(--wine)" />
              <text x="22" y="10" textAnchor="middle" fill="white" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="1.5">START</text>
            </g>
          );
        })()}
      </svg>
    </div>
  );
}

// =============================================================
//  TripMap (main component)
// =============================================================
function TripMap() {
  const auBbox = { lonMin: 142, lonMax: 156, latMin: -39, latMax: -14 };
  const nzBbox = { lonMin: 165.5, lonMax: 179.5, latMin: -47.5, latMax: -34 };

  const auKm = SEGMENTS_AU.filter(s => s.mode === "drive").reduce((a, s) => {
    const c1 = TRIP_CITIES[s.from], c2 = TRIP_CITIES[s.to];
    // approximate km using simple lat/lon distance (~111km/deg)
    const dlat = (c2.lat - c1.lat) * 111;
    const dlon = (c2.lon - c1.lon) * 111 * Math.cos((c1.lat + c2.lat) / 2 * Math.PI / 180);
    return a + Math.sqrt(dlat*dlat + dlon*dlon);
  }, 0);

  return (
    <div className="trip-map" style={{ marginBottom: 56 }}>
      <div className="trip-map-head" style={{
        display: "flex",
        gap: 24,
        justifyContent: "space-between",
        alignItems: "baseline",
        marginBottom: 16,
      }}>
        <div className="eyebrow">Die Route · 29 Tage · zwei Inselstaaten</div>
        <div className="trip-map-legend" style={{ display: "flex", gap: 20, fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--ink-soft)" }}>
          <LegendItem><Swatch type="line" color="var(--wine)" /> Auto / Bus</LegendItem>
          <LegendItem><Swatch type="dash" color="var(--gold)" /> Flug</LegendItem>
          <LegendItem><Swatch type="dot"  color="var(--sage)" /> Fähre</LegendItem>
          <LegendItem><Swatch type="dot2" color="var(--wine)" /> Tagestrip</LegendItem>
        </div>
      </div>

      <div className="trip-map-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
        <MapPanel
          eyebrow="Etappe 1 · Australien"
          title="Sydney → Port Douglas"
          days={13}
          kmTotal={Math.round(auKm)}
          outlines={[{ pts: AUS_OUTLINE }]}
          segments={SEGMENTS_AU}
          cityKeys={["Sydney", "Blue Mountains", "Port Stephens", "Coffs Harbour", "Byron Bay", "Brisbane", "Cairns", "Port Douglas"]}
          bbox={auBbox}
          countryLabel="Australia"
          countryLabelPos={[148, -27]}
          startKey="Sydney"
          hashLabels={{
            "Sydney":         { dx:  9, dy:  5 },
            "Blue Mountains": { dx: -9, dy:  -2, anchor: "end" },
            "Port Stephens":  { dx:  9, dy:  4 },
            "Coffs Harbour":  { dx:  9, dy:  4 },
            "Byron Bay":      { dx:  9, dy:  4 },
            "Brisbane":       { dx:  9, dy:  -4 },
            "Cairns":         { dx: -9, dy:  4, anchor: "end" },
            "Port Douglas":   { dx:  9, dy:  -2 },
          }}
        />
        <MapPanel
          eyebrow="Etappe 2 · Neuseeland"
          title="Auckland → Queenstown"
          days={15}
          kmTotal={2186}
          outlines={[{ pts: NZ_NORTH }, { pts: NZ_SOUTH }]}
          segments={SEGMENTS_NZ}
          cityKeys={["Auckland", "Rotorua", "Tongariro", "Wellington", "Picton", "Franz Josef", "Wanaka", "Mount Cook", "Te Anau", "Milford Sound", "Queenstown"]}
          bbox={nzBbox}
          countryLabel="Aotearoa"
          countryLabelPos={[177, -41.5]}
          hashLabels={{
            "Auckland":      { dx:  9, dy:  4 },
            "Rotorua":       { dx:  9, dy:  4 },
            "Tongariro":     { dx:  9, dy:  4 },
            "Wellington":    { dx:  9, dy:  4 },
            "Picton":        { dx: -9, dy:  0, anchor: "end" },
            "Franz Josef":   { dx: -9, dy: -3, anchor: "end" },
            "Wanaka":        { dx: -9, dy:  4, anchor: "end" },
            "Mount Cook":    { dx:  9, dy: -3 },
            "Te Anau":       { dx: -9, dy: -2, anchor: "end" },
            "Milford Sound": { dx: -9, dy:  6, anchor: "end" },
            "Queenstown":    { dx:  9, dy:  6 },
          }}
        />
      </div>

      <div className="trip-map-summary" style={{
        marginTop: 16,
        padding: "14px 20px",
        background: "var(--paper)",
        border: "1px solid var(--rule)",
        fontFamily: "var(--font-mono)",
        fontSize: 12,
        color: "var(--ink-soft)",
        textAlign: "center",
        letterSpacing: "0.06em",
      }}>
        Hamburg <Arrow/> Sydney <Arrow/> Ostküste <Arrow/> Cairns <FlightIcon/> <strong style={{ color: "var(--ink)" }}>Auckland</strong> <Arrow/> Nordinsel <Arrow/> Südinsel <Arrow/> Queenstown <FlightIcon/> Auckland <FlightIcon/> Hamburg
      </div>
    </div>
  );
}

function Swatch({ type, color }) {
  const common = { display: "inline-block", width: 22, verticalAlign: "middle", marginRight: 6, height: 0 };
  if (type === "dash") return <span style={{ ...common, borderTop: `2px dashed ${color}` }} />;
  if (type === "dot")  return <span style={{ ...common, borderTop: `2px dotted ${color}` }} />;
  if (type === "dot2") return <span style={{ ...common, borderTop: `1.5px dashed ${color}`, opacity: 0.6 }} />;
  return <span style={{ ...common, borderTop: `2px solid ${color}` }} />;
}
function LegendItem({ children }) {
  return <span style={{ display: "inline-flex", alignItems: "center" }}>{children}</span>;
}
function Arrow() {
  return <span style={{ margin: "0 6px", color: "var(--ink-mute)" }}>→</span>;
}
function FlightIcon() {
  return <span style={{ margin: "0 6px", color: "var(--gold-deep)" }}>✈</span>;
}

Object.assign(window, { TripMap });
