import { createSignal, createMemo, Show, For } from "solid-js";
import { useI18n } from "../providers/i18n-provider";
import { Card, CardHeader, CardTitle, CardDescription, CardContent, Button, Tabs, TabsList, TabsTrigger, TabsContent, Tooltip, Badge, Input, Select } from "./ui";
import { BookraCharacter } from "./bookra-character";
import { LocationMap } from "./location-map";
import {
  DEFAULT_MAP_STYLE_ID,
  MAP_STYLE_OPTIONS,
  resolveLocationInput,
  resolveMapTileStyle,
  type MapCoordinates,
} from "../lib/map";

export type WidgetType = "iframe" | "button" | "inline" | "modal" | "floating" | "map";
export type WidgetTheme = "light" | "dark" | "auto";
export type WidgetSize = "compact" | "default" | "full";
export type WidgetPosition = "bottom-right" | "bottom-left" | "top-right" | "top-left";
type CodeFormat = "html" | "react" | "vue" | "js" | "php" | "solid" | "astro" | "ts" | "angular" | "svelte";

interface WidgetConfig {
  tenantSlug: string;
  publicBookingUrl: string;
  tenantName: string;
  primaryColor?: string;
}

interface WidgetOption {
  type: WidgetType;
  icon: () => any;
  title: string;
  description: string;
}

interface WidgetBuilderProps {
  config: WidgetConfig;
}

// Lucide Icons
const CopyIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
  </svg>
);

const CheckIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <polyline points="20 6 9 17 4 12" />
  </svg>
);

const CodeIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <polyline points="16 18 22 12 16 6" />
    <polyline points="8 6 2 12 8 18" />
  </svg>
);

const ExternalLinkIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
    <polyline points="15 3 21 3 21 9" />
    <line x1="10" y1="14" x2="21" y2="3" />
  </svg>
);

const IframeIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <rect x="3" y="3" width="18" height="18" rx="2" />
    <line x1="3" y1="9" x2="21" y2="9" />
    <line x1="9" y1="21" x2="9" y2="9" />
  </svg>
);

const ButtonIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <rect x="4" y="8" width="16" height="8" rx="4" />
  </svg>
);

const CalendarIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <rect x="3" y="4" width="18" height="18" rx="2" />
    <line x1="16" y1="2" x2="16" y2="6" />
    <line x1="8" y1="2" x2="8" y2="6" />
    <line x1="3" y1="10" x2="21" y2="10" />
  </svg>
);

const ModalIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <rect x="3" y="3" width="18" height="18" rx="2" />
    <path d="M9 3v18" />
    <path d="M15 3v18" />
    <path d="M3 9h18" />
    <path d="M3 15h18" />
  </svg>
);

const FloatingIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <circle cx="12" cy="12" r="10" />
    <line x1="12" y1="8" x2="12" y2="16" />
    <line x1="8" y1="12" x2="16" y2="12" />
  </svg>
);

const SunIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <circle cx="12" cy="12" r="4" />
    <path d="M12 2v2" />
    <path d="M12 20v2" />
    <path d="M4.93 4.93l1.41 1.41" />
    <path d="M17.66 17.66l1.41 1.41" />
    <path d="M2 12h2" />
    <path d="M20 12h2" />
    <path d="M6.34 17.66l-1.41 1.41" />
    <path d="M19.07 4.93l-1.41 1.41" />
  </svg>
);

const MoonIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
  </svg>
);

const RefreshIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
    <path d="M3 3v5h5" />
    <path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" />
    <path d="M16 21h5v-5" />
  </svg>
);

const LockIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
    <path d="M7 11V7a5 5 0 0 1 10 0v4" />
  </svg>
);

const DragIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <circle cx="9" cy="12" r="1" />
    <circle cx="9" cy="5" r="1" />
    <circle cx="9" cy="19" r="1" />
    <circle cx="15" cy="12" r="1" />
    <circle cx="15" cy="5" r="1" />
    <circle cx="15" cy="19" r="1" />
  </svg>
);

const MoveIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <polyline points="5 9 2 12 5 15" />
    <polyline points="9 5 12 2 15 5" />
    <polyline points="15 19 12 22 9 19" />
    <polyline points="19 15 22 12 19 9" />
    <line x1="2" y1="12" x2="22" y2="12" />
    <line x1="12" y1="2" x2="12" y2="22" />
  </svg>
);

const PaletteIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <circle cx="13.5" cy="6.5" r=".5" fill="currentColor" />
    <circle cx="17.5" cy="10.5" r=".5" fill="currentColor" />
    <circle cx="8.5" cy="7.5" r=".5" fill="currentColor" />
    <circle cx="6.5" cy="12.5" r=".5" fill="currentColor" />
    <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.01 17.461 2 12 2z" />
  </svg>
);

const MapIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <path d="M9 18 3 21V6l6-3 6 3 6-3v15l-6 3-6-3Z" />
    <path d="M9 3v15" />
    <path d="M15 6v15" />
  </svg>
);

const EyeIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
    <circle cx="12" cy="12" r="3" />
  </svg>
);

const DEFAULT_MAP_COORDINATES: MapCoordinates = {
  latitude: 50.0755,
  longitude: 14.4378,
  zoom: 15,
  address: "Prague, Czechia",
  source: "coordinates",
};

function json(value: string): string {
  return JSON.stringify(value);
}

function generatedMapElementId(tenantSlug: string): string {
  return `bookra-map-${tenantSlug}`;
}

function safeHexColor(color: string): string {
  return /^#[0-9a-fA-F]{3,8}$/.test(color.trim()) ? color.trim() : "#a65c3e";
}

export function WidgetBuilder(props: WidgetBuilderProps) {
  const i18n = useI18n();
  const [selectedType, setSelectedType] = createSignal<WidgetType>("iframe");
  const [selectedTheme, setSelectedTheme] = createSignal<WidgetTheme>("auto");
  const [selectedSize, setSelectedSize] = createSignal<WidgetSize>("default");
  const [selectedPosition, setSelectedPosition] = createSignal<WidgetPosition>("bottom-right");
  const [copiedSnippet, setCopiedSnippet] = createSignal<string | null>(null);
  const [copyError, setCopyError] = createSignal<string | null>(null);
  const [showPreview, setShowPreview] = createSignal(true);
  const [draggedIndex, setDraggedIndex] = createSignal<number | null>(null);
  const [customColor, setCustomColor] = createSignal(props.config.primaryColor || "#a65c3e");
  const [borderRadius, setBorderRadius] = createSignal(12);
  const [shadowIntensity, setShadowIntensity] = createSignal(20);
  const [buttonText, setButtonText] = createSignal(i18n.t("widget.button.text"));
  const [mapLocationInput, setMapLocationInput] = createSignal("Prague, Czechia");
  const [mapCoordinates, setMapCoordinates] = createSignal<MapCoordinates>(DEFAULT_MAP_COORDINATES);
  const [mapStyle, setMapStyle] = createSignal(DEFAULT_MAP_STYLE_ID);
  const [customTileUrl, setCustomTileUrl] = createSignal("");
  const [mapHeight, setMapHeight] = createSignal(360);
  const [mapZoom, setMapZoom] = createSignal(15);
  const [mapMarkerColor, setMapMarkerColor] = createSignal(props.config.primaryColor || "#a65c3e");
  const [mapMessage, setMapMessage] = createSignal<string | null>(null);
  const [resolvingMap, setResolvingMap] = createSignal(false);
  
  // Widget order state for drag and drop
  const [widgetOrder, setWidgetOrder] = createSignal<WidgetType[]>(["iframe", "button", "inline", "modal", "floating", "map"]);

  const widgetId = createMemo(() => `bookra-widget-${props.config.tenantSlug}`);
  
  const apiBaseUrl = import.meta.env.VITE_BOOKRA_API_URL ?? "https://api.bookra.io";
  const widgetScriptUrl = `${apiBaseUrl}/v1/public/widget.js`;

  const widgetOptionsMap: Record<WidgetType, WidgetOption> = {
    iframe: {
      type: "iframe",
      icon: IframeIcon,
      title: i18n.t("widget.type.iframe.title"),
      description: i18n.t("widget.type.iframe.desc"),
    },
    button: {
      type: "button",
      icon: ButtonIcon,
      title: i18n.t("widget.type.button.title"),
      description: i18n.t("widget.type.button.desc"),
    },
    inline: {
      type: "inline",
      icon: CalendarIcon,
      title: i18n.t("widget.type.inline.title"),
      description: i18n.t("widget.type.inline.desc"),
    },
    modal: {
      type: "modal",
      icon: ModalIcon,
      title: i18n.t("widget.type.modal.title"),
      description: i18n.t("widget.type.modal.desc"),
    },
    floating: {
      type: "floating",
      icon: FloatingIcon,
      title: i18n.t("widget.type.floating.title"),
      description: i18n.t("widget.type.floating.desc"),
    },
    map: {
      type: "map",
      icon: MapIcon,
      title: i18n.t("widget.type.map.title"),
      description: i18n.t("widget.type.map.desc"),
    },
  };

  const resolveMapLocation = async () => {
    setResolvingMap(true);
    setMapMessage(null);
    try {
      const result = await resolveLocationInput(mapLocationInput());
      if (!result) {
        setMapMessage(i18n.t("widget.map.noLocation"));
        return;
      }
      setMapCoordinates({
        ...result,
        zoom: result.zoom ?? mapZoom(),
      });
      setMapZoom(result.zoom ?? mapZoom());
      setMapMessage(result.address ? `${i18n.t("widget.map.resolved")}: ${result.address}` : i18n.t("widget.map.resolved"));
    } catch (error) {
      setMapMessage(error instanceof Error ? error.message : "Location search failed.");
    } finally {
      setResolvingMap(false);
    }
  };

  const activeMapTileStyle = createMemo(() => resolveMapTileStyle(mapStyle(), customTileUrl()));

  const generateMapCode = (format: CodeFormat) => {
    const coords = mapCoordinates();
    const style = activeMapTileStyle();
    const elementId = generatedMapElementId(props.config.tenantSlug);
    const markerColor = safeHexColor(mapMarkerColor());
    const label = props.config.tenantName;
    const address = coords.address ?? mapLocationInput();
    const zoom = mapZoom();
    const height = mapHeight();

    if (format === "html") {
      return `<!-- Bookra Location Map - ${props.config.tenantName} -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<div id="${elementId}" style="width:100%;height:${height}px;border-radius:12px;overflow:hidden;border:1px solid #e8dfd4;"></div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
(function () {
  var map = L.map(${json(elementId)}, { scrollWheelZoom: false }).setView([${coords.latitude}, ${coords.longitude}], ${zoom});
  L.tileLayer(${json(style.url)}, {
    attribution: ${json(style.attribution)},
    maxZoom: 19
  }).addTo(map);

  function escapeHtml(value) {
    return String(value || "")
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  }

  var icon = L.divIcon({
    className: "bookra-map-marker",
    html: '<span style="display:block;width:28px;height:28px;border-radius:999px;background:${markerColor};border:3px solid white;box-shadow:0 10px 24px rgba(0,0,0,.25);"></span>',
    iconSize: [28, 28],
    iconAnchor: [14, 14]
  });
  L.marker([${coords.latitude}, ${coords.longitude}], { icon: icon })
    .addTo(map)
    .bindPopup("<strong>" + escapeHtml(${json(label)}) + "</strong><br>" + escapeHtml(${json(address)}));
})();
</script>`;
    }

    if (format === "js" || format === "ts") {
      return `import L from "leaflet";
import "leaflet/dist/leaflet.css";

export function mountBookraLocationMap(element: HTMLElement) {
  const map = L.map(element, { scrollWheelZoom: false }).setView([${coords.latitude}, ${coords.longitude}], ${zoom});

  L.tileLayer(${json(style.url)}, {
    attribution: ${json(style.attribution)},
    maxZoom: 19,
  }).addTo(map);

  const icon = L.divIcon({
    className: "bookra-map-marker",
    html: ${json(`<span style="display:block;width:28px;height:28px;border-radius:999px;background:${markerColor};border:3px solid white;box-shadow:0 10px 24px rgba(0,0,0,.25);"></span>`)},
    iconSize: [28, 28],
    iconAnchor: [14, 14],
  });

  L.marker([${coords.latitude}, ${coords.longitude}], { icon })
    .addTo(map)
    .bindPopup(${json(`${label}<br>${address}`)});

  return map;
}`;
    }

    if (format === "solid") {
      return `import { onCleanup, onMount } from "solid-js";
import L from "leaflet";
import "leaflet/dist/leaflet.css";

export function BookraLocationMap() {
  let el: HTMLDivElement | undefined;
  let map: L.Map | undefined;

  onMount(() => {
    if (!el) return;
    map = L.map(el, { scrollWheelZoom: false }).setView([${coords.latitude}, ${coords.longitude}], ${zoom});
    L.tileLayer(${json(style.url)}, {
      attribution: ${json(style.attribution)},
      maxZoom: 19,
    }).addTo(map);
    L.marker([${coords.latitude}, ${coords.longitude}]).addTo(map).bindPopup(${json(`${label}<br>${address}`)});
  });

  onCleanup(() => map?.remove());

  return <div ref={el} style={{ width: "100%", height: "${height}px", "border-radius": "12px", overflow: "hidden" }} />;
}`;
    }

    if (format === "react") {
      return `import { useEffect, useRef } from "react";
import L from "leaflet";
import "leaflet/dist/leaflet.css";

export function BookraLocationMap() {
  const ref = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!ref.current) return;
    const map = L.map(ref.current, { scrollWheelZoom: false }).setView([${coords.latitude}, ${coords.longitude}], ${zoom});
    L.tileLayer(${json(style.url)}, {
      attribution: ${json(style.attribution)},
      maxZoom: 19,
    }).addTo(map);
    L.marker([${coords.latitude}, ${coords.longitude}]).addTo(map).bindPopup(${json(`${label}<br>${address}`)});
    return () => map.remove();
  }, []);

  return <div ref={ref} style={{ width: "100%", height: ${height}, borderRadius: 12, overflow: "hidden" }} />;
}`;
    }

    return `<!-- Use the HTML tab for this styled map embed. Current style: ${style.name}. -->`;
  };

  // Drag and drop handlers
  const [dropTargetIndex, setDropTargetIndex] = createSignal<number | null>(null);

  const handleDragStart = (index: number) => {
    setDraggedIndex(index);
  };

  const handleDragOver = (e: DragEvent, index: number) => {
    e.preventDefault();
    setDropTargetIndex(index);
    const draggedIdx = draggedIndex();
    if (draggedIdx === null || draggedIdx === index) return;
    const newOrder = [...widgetOrder()];
    const [removed] = newOrder.splice(draggedIdx, 1);
    newOrder.splice(index, 0, removed);
    setWidgetOrder(newOrder);
    setDraggedIndex(index);
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
    setDropTargetIndex(null);
  };

  const generateCode = (type: WidgetType, format: CodeFormat) => {
    const theme = selectedTheme();
    const size = selectedSize();
    const primaryColor = customColor();
    const radius = borderRadius();
    const shadow = shadowIntensity();
    const btnText = buttonText();
    const position = selectedPosition();
    
    const commonAttributes = `
  data-tenant="${props.config.tenantSlug}" 
  data-theme="${theme}" 
  data-size="${size}"
  data-color="${primaryColor}"
  data-radius="${radius}"
  data-shadow="${shadow}"`;

    const shadowStyle = shadow > 0 ? `box-shadow: 0 4px ${shadow}px rgba(0,0,0,0.1);` : '';

    if (type === "map") {
      return generateMapCode(format);
    }

    switch (type) {
      case "iframe":
        if (format === "html") {
          return `<!-- Bookra Booking Widget - ${props.config.tenantName} -->
<iframe 
  id="${widgetId()}"
  src="${props.config.publicBookingUrl}" 
  title="Book ${props.config.tenantName}"
  style="width:100%; min-height:${size === 'compact' ? '400px' : size === 'full' ? '100vh' : '760px'}; border:none; border-radius:${radius}px;${shadowStyle}"
  loading="lazy"
></iframe>`;
        } else if (format === "react") {
          return `// Bookra Booking Widget Component
export function BookraBookingWidget() {
  return (
    <iframe
      id="${widgetId()}"
      src="${props.config.publicBookingUrl}"
      title="Book ${props.config.tenantName}"
      style={{ 
        width: "100%", 
        minHeight: ${size === 'compact' ? 400 : size === 'full' ? '100vh' : 760}, 
        border: "none", 
        borderRadius: ${radius},
        ${shadow > 0 ? `boxShadow: "0 4px ${shadow}px rgba(0,0,0,0.1)"` : ''}
      }}
      loading="lazy"
    />
  );
}`;
        } else if (format === "vue") {
          return `<!-- Bookra Booking Widget - Vue -->
<template>
  <iframe
    id="${widgetId()}"
    :src="bookingUrl"
    title="Book ${props.config.tenantName}"
    style="width:100%; min-height:${size === 'compact' ? '400px' : size === 'full' ? '100vh' : '760px'}; border:none; border-radius:${radius}px;${shadowStyle}"
    loading="lazy"
  ></iframe>
</template>

<script setup>
const bookingUrl = "${props.config.publicBookingUrl}";
</script>`;
        }
        break;

      case "button":
        if (format === "html") {
          return `<!-- Bookra Booking Button -->
<button 
  id="${widgetId()}"
  class="bookra-booking-btn"
  onclick="window.open('${props.config.publicBookingUrl}', '_blank')"
  style="
    background: ${primaryColor};
    color: white;
    padding: 14px 28px;
    border: none;
    border-radius: ${radius}px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s;
    ${shadowStyle}
  "
  onmouseover="this.style.transform='translateY(-2px)';this.style.boxShadow='0 6px ${shadow + 4}px rgba(0,0,0,0.15)'"
  onmouseout="this.style.transform='translateY(0)';this.style.boxShadow='${shadow > 0 ? `0 4px ${shadow}px rgba(0,0,0,0.1)` : 'none'}'"
>
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
    <line x1="16" y1="2" x2="16" y2="6"/>
    <line x1="8" y1="2" x2="8" y2="6"/>
    <line x1="3" y1="10" x2="21" y2="10"/>
  </svg>
  ${btnText}
</button>`;
        } else if (format === "react") {
          return `// Bookra Booking Button Component
export function BookraBookingButton() {
  const [isHovered, setIsHovered] = createSignal(false);
  
  return (
    <button
      onClick={() => window.open("${props.config.publicBookingUrl}", "_blank")}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      style={{
        background: "${primaryColor}",
        color: "white",
        padding: "14px 28px",
        border: "none",
        borderRadius: ${radius},
        fontSize: 16,
        fontWeight: 600,
        cursor: "pointer",
        display: "inline-flex",
        alignItems: "center",
        gap: 8,
        transform: isHovered() ? "translateY(-2px)" : "translateY(0)",
        boxShadow: isHovered() 
          ? "0 6px ${shadow + 4}px rgba(0,0,0,0.15)" 
          : ${shadow > 0 ? `"0 4px ${shadow}px rgba(0,0,0,0.1)"` : "none"},
        transition: "all 0.2s ease"
      }}
    >
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <rect x="3" y="4" width="18" height="18" rx="2"/>
        <line x1="16" y1="2" x2="16" y2="6"/>
        <line x1="8" y1="2" x2="8" y2="6"/>
        <line x1="3" y1="10" x2="21" y2="10"/>
      </svg>
      ${btnText}
    </button>
  );
}`;
        }
        break;

      case "inline":
        if (format === "html") {
          return `<!-- Bookra Inline Calendar Widget -->
<div id="${widgetId()}" class="bookra-widget"${commonAttributes}></div>

<!-- Load the Bookra Widget Script -->
<script 
  src="${widgetScriptUrl}" 
  async 
  defer
  data-widget-id="${widgetId()}"
></script>`;
        } else if (format === "js") {
          return `// Initialize Bookra Widget
(function() {
  const script = document.createElement('script');
  script.src = "${widgetScriptUrl}";
  script.async = true;
  script.defer = true;
  script.setAttribute('data-widget-id', "${widgetId()}");
  document.head.appendChild(script);
  
  // Create widget container
  const container = document.createElement('div');
  container.id = "${widgetId()}";
  container.className = "bookra-widget";
  container.setAttribute('data-tenant', "${props.config.tenantSlug}");
  container.setAttribute('data-theme', "${theme}");
  container.setAttribute('data-size', "${size}");
  document.body.appendChild(container);
})();`;
        }
        break;

      case "modal":
        if (format === "html") {
          return `<!-- Bookra Modal Widget -->
<button 
  id="bookra-trigger-${props.config.tenantSlug}"
  class="bookra-modal-trigger"
  onclick="document.getElementById('${widgetId()}-modal').style.display='flex'"
  style="
    background: ${primaryColor};
    color: white;
    padding: 14px 28px;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
  "
>
  ${i18n.t("widget.modal.trigger")}
</button>

<div 
  id="${widgetId()}-modal"
  class="bookra-modal"
  onclick="if(event.target===this)this.style.display='none'"
  style="
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.5);
    z-index: 9999;
    align-items: center;
    justify-content: center;
    padding: 20px;
  "
>
  <div style="background:white; border-radius:16px; width:100%; max-width:900px; height:90vh; position:relative;">
    <button 
      onclick="document.getElementById('${widgetId()}-modal').style.display='none'"
      style="
        position: absolute;
        top: 16px;
        right: 16px;
        background: #f5f5f5;
        border: none;
        width: 36px;
        height: 36px;
        border-radius: 50%;
        cursor: pointer;
        font-size: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
      "
    >✕</button>
    <iframe 
      src="${props.config.publicBookingUrl}"
      style="width:100%; height:100%; border:none; border-radius:16px;"
    ></iframe>
  </div>
</div>`;
        }
        break;

      case "floating":
        if (format === "html") {
          return `<!-- Bookra Floating Widget -->
<div id="${widgetId()}" class="bookra-widget-floating"${commonAttributes}></div>
<script src="${widgetScriptUrl}" async defer data-widget-id="${widgetId()}"></script>`;
        } else if (format === "js") {
          return `// Bookra Floating Widget
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "${widgetScriptUrl}";
  js.setAttribute('data-widget-id', "${widgetId()}");
  js.setAttribute('data-tenant', "${props.config.tenantSlug}");
  js.setAttribute('data-theme', "${theme}");
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'bookra-widget-js'));`;
        }
        break;
    }

    // PHP Code Generation
    if (format === "php") {
      return `<?php
// Bookra Booking Widget for ${props.config.tenantName}
$tenantSlug = "${props.config.tenantSlug}";
$bookingUrl = "${props.config.publicBookingUrl}";
$primaryColor = "${primaryColor}";
$theme = "${theme}";
?>

<!-- Bookra Booking Widget -->
<div id="<?php echo $tenantSlug; ?>-widget" class="bookra-widget">
  <iframe 
    src="<?php echo htmlspecialchars($bookingUrl); ?>" 
    title="Book <?php echo htmlspecialchars($tenantSlug); ?>"
    style="width:100%; min-height:760px; border:none; border-radius:12px;"
    loading="lazy"
  ></iframe>
</div>

<?php
// Alternative: Button only
function renderBookraButton($url, $color) {
    return '<button 
        onclick="window.open(\'' . htmlspecialchars($url) . '\', \'_blank\')"
        style="background:' . htmlspecialchars($color) . ';color:white;padding:14px 28px;border:none;border-radius:8px;font-size:16px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:8px;"
    >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline;vertical-align:middle;margin-right:4px;"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg> Book appointment
    </button>';
}
// echo renderBookraButton($bookingUrl, $primaryColor);
?>`;
    }

    // SolidJS Code Generation
    if (format === "solid") {
      return `// Bookra Booking Widget - SolidJS Component
import { createSignal, onMount } from "solid-js";

export function BookraBookingWidget() {
  const [isLoaded, setIsLoaded] = createSignal(false);
  const tenantSlug = "${props.config.tenantSlug}";
  const bookingUrl = "${props.config.publicBookingUrl}";
  const primaryColor = "${primaryColor}";

  return (
    <div class="bookra-widget-container">
      <iframe
        src={bookingUrl}
        title={\`Book \${tenantSlug}\`}
        style={{
          width: "100%",
          "min-height": "760px",
          border: "none",
          "border-radius": "12px",
          opacity: isLoaded() ? 1 : 0,
          transition: "opacity 0.3s"
        }}
        loading="lazy"
        onLoad={() => setIsLoaded(true)}
      />
      {!isLoaded() && (
        <div style={{ 
          position: "absolute", 
          inset: 0, 
          display: "flex", 
          "align-items": "center", 
          "justify-content": "center",
          background: "#f5f5f5"
        }}>
          Loading booking widget...
        </div>
      )}
    </div>
  );
}

// Button variant
export function BookraBookingButton() {
  const bookingUrl = "${props.config.publicBookingUrl}";
  const primaryColor = "${primaryColor}";

  return (
    <button
      onClick={() => window.open(bookingUrl, "_blank")}
      style={{
        background: primaryColor,
        color: "white",
        padding: "14px 28px",
        border: "none",
        "border-radius": "8px",
        "font-size": "16px",
        "font-weight": 600,
        cursor: "pointer",
        display: "inline-flex",
        "align-items": "center",
        gap: "8px"
      }}
    >
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <rect x="3" y="4" width="18" height="18" rx="2"/>
        <line x1="16" y1="2" x2="16" y2="6"/>
        <line x1="8" y1="2" x2="8" y2="6"/>
        <line x1="3" y1="10" x2="21" y2="10"/>
      </svg>
      Book appointment
    </button>
  );
}`;
    }

    // Astro Code Generation
    if (format === "astro") {
      return `---
// Bookra Booking Widget - Astro Component
// Props interface
interface Props {
  tenantSlug?: string;
  theme?: "light" | "dark" | "auto";
  size?: "compact" | "default" | "full";
}

const { 
  tenantSlug = "${props.config.tenantSlug}",
  theme = "${theme}",
  size = "${size}"
} = Astro.props;

const bookingUrl = "${props.config.publicBookingUrl}";
const primaryColor = "${primaryColor}";
const height = size === "compact" ? "400px" : size === "full" ? "100vh" : "760px";
---

<!-- Bookra Booking Widget -->
<div class="bookra-widget" data-theme={theme}>
  <iframe
    src={bookingUrl}
    title={\`Book \${tenantSlug}\`}
    style={\`width:100%; height:\${height}; border:none; border-radius:12px;\`}
    loading="lazy"
  ></iframe>
</div>

<style define:vars={{ primaryColor }}>
  .bookra-widget {
    width: 100%;
    position: relative;
  }
  
  .bookra-widget iframe {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
  
  @media (prefers-color-scheme: dark) {
    .bookra-widget[data-theme="auto"] iframe {
      filter: invert(0.95) hue-rotate(180deg);
    }
  }
</style>

<script>
  // Client-side interactivity if needed
  console.log('[Bookra Widget] Loaded for ${props.config.tenantSlug}');
</script>`;
    }

    // TypeScript Code Generation
    if (format === "ts") {
      return `// Bookra Booking Widget - TypeScript
// types.ts
export interface BookraWidgetConfig {
  tenantSlug: string;
  theme?: "light" | "dark" | "auto";
  size?: "compact" | "default" | "full";
  primaryColor?: string;
}

export const BOOKING_URL = "${props.config.publicBookingUrl}";
export const TENANT_SLUG = "${props.config.tenantSlug}";

// widget.ts
export function createBookraWidget(config: BookraWidgetConfig): HTMLIFrameElement {
  const iframe = document.createElement("iframe");
  iframe.src = BOOKING_URL;
  iframe.title = \`Book \${config.tenantSlug}\`;
  iframe.style.cssText = \`
    width: 100%;
    min-height: \${config.size === "compact" ? "400px" : config.size === "full" ? "100vh" : "760px"};
    border: none;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  \`;
  iframe.loading = "lazy";
  
  // Add to container
  const container = document.getElementById(config.tenantSlug + "-widget");
  if (container) {
    container.appendChild(iframe);
  }
  
  return iframe;
}

// Usage:
// const widget = createBookraWidget({ 
//   tenantSlug: "${props.config.tenantSlug}",
//   theme: "${theme}",
//   size: "${size}"
// });`;
    }

    // Angular Code Generation
    if (format === "angular") {
      return `<!-- Bookra Booking Widget - Angular Component -->

<!-- bookra-widget.component.ts -->
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-bookra-widget',
  templateUrl: './bookra-widget.component.html',
  styleUrls: ['./bookra-widget.component.css']
})
export class BookraWidgetComponent implements OnInit {
  @Input() tenantSlug: string = "${props.config.tenantSlug}";
  @Input() theme: 'light' | 'dark' | 'auto' = "${theme}";
  @Input() size: 'compact' | 'default' | 'full' = "${size}";
  @Input() primaryColor: string = "${primaryColor}";
  
  bookingUrl: string = "${props.config.publicBookingUrl}";
  isLoading: boolean = true;
  
  ngOnInit(): void {
    console.log('[Bookra Widget] Initializing for', this.tenantSlug);
  }
  
  onIframeLoad(): void {
    this.isLoading = false;
  }
  
  getIframeHeight(): string {
    switch (this.size) {
      case 'compact': return '400px';
      case 'full': return '100vh';
      default: return '760px';
    }
  }
}

<!-- bookra-widget.component.html -->
<div class="bookra-widget-container" [attr.data-theme]="theme">
  <div *ngIf="isLoading" class="widget-loading">
    Loading booking widget...
  </div>
  <iframe
    [src]="bookingUrl"
    title="Book {{ tenantSlug }}"
    [style.height]="getIframeHeight()"
    style="width:100%; border:none; border-radius:12px;"
    loading="lazy"
    (load)="onIframeLoad()"
    [style.opacity]="isLoading ? 0 : 1"
    [style.transition]="'opacity 0.3s'"
  ></iframe>
</div>

<!-- bookra-widget.component.css -->
.bookra-widget-container {
  position: relative;
  width: 100%;
}

.widget-loading {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 12px;
}

/* Usage in parent template:
<app-bookra-widget
  tenantSlug="${props.config.tenantSlug}"
  theme="${theme}"
  size="${size}"
  primaryColor="${primaryColor}"
></app-bookra-widget>
-->`;
    }

    // Svelte Code Generation
    if (format === "svelte") {
      return `<!-- Bookra Booking Widget - Svelte Component -->
<!-- BookraWidget.svelte -->
<script lang="ts">
  export let tenantSlug: string = "${props.config.tenantSlug}";
  export let theme: "light" | "dark" | "auto" = "${theme}";
  export let size: "compact" | "default" | "full" = "${size}";
  export let primaryColor: string = "${primaryColor}";
  
  const bookingUrl = "${props.config.publicBookingUrl}";
  let isLoaded = false;
  
  $: height = size === "compact" ? "400px" : size === "full" ? "100vh" : "760px";
  
  function handleLoad() {
    isLoaded = true;
  }
</script>

<div class="bookra-widget" data-theme={theme}>
  {#if !isLoaded}
    <div class="loading">
      Loading booking widget...
    </div>
  {/if}
  <iframe
    src={bookingUrl}
    title={\`Book \${tenantSlug}\`}
    style="width:100%; height:{height}; border:none; border-radius:12px;"
    style:opacity={isLoaded ? 1 : 0}
    style:transition="opacity 0.3s"
    loading="lazy"
    on:load={handleLoad}
  />
</div>

<style>
  .bookra-widget {
    position: relative;
    width: 100%;
  }
  
  .loading {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    border-radius: 12px;
  }
  
  iframe {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
</style>

<!-- Usage:
<BookraWidget 
  tenantSlug="${props.config.tenantSlug}"
  theme="${theme}"
  size="${size}"
  primaryColor="${primaryColor}"
/> -->`;
    }

    return "// Widget code generation not available for this combination";
  };

  const copyToClipboard = async (text: string, snippetId: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedSnippet(snippetId);
      setCopyError(null);
      setTimeout(() => setCopiedSnippet(null), 2000);
    } catch (err) {
      setCopyError(i18n.locale() === 'cs' ? 'Kopírování se nezdařilo. Zkuste to znovu.' : 'Copy failed. Please try again.');
      setTimeout(() => setCopyError(null), 3000);
    }
  };

  const currentCode = createMemo(() => {
    const type = selectedType();
    return {
      html: generateCode(type, "html"),
      react: generateCode(type, "react"),
      vue: generateCode(type, "vue"),
      js: generateCode(type, "js"),
      php: generateCode(type, "php"),
      solid: generateCode(type, "solid"),
      astro: generateCode(type, "astro"),
      ts: generateCode(type, "ts"),
      angular: generateCode(type, "angular"),
      svelte: generateCode(type, "svelte"),
    };
  });

  return (
    <div class="space-y-8">
      {/* Widget Type Selector - Draggable */}
      <Card class="surface-elevated">
        <CardHeader>
          <div class="flex items-center gap-3">
            <MoveIcon />
            <div>
              <CardTitle class="text-lg">{i18n.t("widget.types.title")}</CardTitle>
              <CardDescription>{i18n.t("widget.types.desc")}</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div class="space-y-2">
            <For each={widgetOrder()}>
              {(type, index) => {
                const option = widgetOptionsMap[type];
                const Icon = option.icon;
                return (
                  <div
                    draggable={true}
                    onDragStart={() => handleDragStart(index())}
                    onDragOver={(e) => handleDragOver(e, index())}
                    onDragEnd={handleDragEnd}
                    class={`p-4 rounded-card border-2 text-left transition-all duration-200 cursor-move group ${
                      selectedType() === type
                        ? "border-accent bg-accent/5"
                        : "border-border hover:border-accent/50 hover:bg-canvas-subtle"
                    } ${draggedIndex() === index() ? "opacity-40 scale-[0.98] shadow-lg ring-2 ring-accent/20" : ""} ${dropTargetIndex() === index() && draggedIndex() !== index() ? "border-accent/60 bg-accent/5" : ""}`}
                    onClick={() => setSelectedType(type)}
                  >
                    <div class="flex items-center gap-3">
                      <div class="text-ink-muted group-hover:text-accent transition-colors">
                        <DragIcon />
                      </div>
                      <div class="w-10 h-10 rounded-lg bg-accent/10 flex items-center justify-center text-accent">
                        <Icon />
                      </div>
                      <div class="flex-1">
                        <h4 class="font-display font-semibold text-ink">{option.title}</h4>
                        <p class="text-sm text-ink-muted">{option.description}</p>
                      </div>
                      <Show when={selectedType() === type}>
                        <div class="w-6 h-6 rounded-full bg-accent text-white flex items-center justify-center text-sm">
                          <CheckIcon />
                        </div>
                      </Show>
                    </div>
                  </div>
                );
              }}
            </For>
          </div>
        </CardContent>
      </Card>

      {/* Theme & Size Options */}
      <Card class="surface-elevated">
        <CardHeader>
          <CardTitle class="text-lg">{i18n.t("widget.customize.title")}</CardTitle>
          <CardDescription>{i18n.t("widget.customize.desc")}</CardDescription>
        </CardHeader>
        <CardContent class="space-y-6">
          {/* Theme Selection */}
          <div class="space-y-3">
            <label class="text-sm font-medium text-ink">{i18n.t("widget.theme.label")}</label>
            <div class="flex flex-wrap gap-2">
              {[
                { value: "light", label: i18n.t("widget.theme.light"), Icon: SunIcon },
                { value: "dark", label: i18n.t("widget.theme.dark"), Icon: MoonIcon },
                { value: "auto", label: i18n.t("widget.theme.auto"), Icon: RefreshIcon },
              ].map((theme) => (
                <button
                  class={`px-4 py-2 rounded-button text-sm font-medium transition-all inline-flex items-center gap-2 ${
                    selectedTheme() === theme.value
                      ? "bg-accent text-white"
                      : "bg-canvas-subtle text-ink-muted hover:text-ink"
                  }`}
                  onClick={() => setSelectedTheme(theme.value as WidgetTheme)}
                >
                  <theme.Icon />
                  {theme.label}
                </button>
              ))}
            </div>
          </div>

          {/* Size Selection */}
          <div class="space-y-3">
            <label class="text-sm font-medium text-ink">{i18n.t("widget.size.label")}</label>
            <div class="flex flex-wrap gap-2">
              {[
                { value: "compact", label: i18n.t("widget.size.compact") },
                { value: "default", label: i18n.t("widget.size.default") },
                { value: "full", label: i18n.t("widget.size.full") },
              ].map((size) => (
                <button
                  class={`px-4 py-2 rounded-button text-sm font-medium transition-all ${
                    selectedSize() === size.value
                      ? "bg-accent text-white"
                      : "bg-canvas-subtle text-ink-muted hover:text-ink"
                  }`}
                  onClick={() => setSelectedSize(size.value as WidgetSize)}
                >
                  {size.label}
                </button>
              ))}
            </div>
          </div>

          {/* Custom Styling */}
          <div class="space-y-4 pt-4 border-t border-border">
            <div class="flex items-center gap-2">
              <PaletteIcon />
              <label class="text-sm font-medium text-ink">{i18n.t("widget.styling.title")}</label>
            </div>
            
            {/* Primary Color */}
            <div class="space-y-2">
              <label class="text-xs text-ink-muted">{i18n.t("widget.styling.color")}</label>
              <div class="flex items-center gap-3">
                <input
                  type="color"
                  value={customColor()}
                  onInput={(e) => setCustomColor(e.currentTarget.value)}
                  class="w-10 h-10 rounded-lg border border-border cursor-pointer"
                />
                <Input
                  value={customColor()}
                  onInput={(e) => setCustomColor(e.currentTarget.value)}
                  class="flex-1"
                  placeholder="#a65c3e"
                />
              </div>
            </div>

            {/* Border Radius */}
            <div class="space-y-2">
              <label class="text-xs text-ink-muted">{i18n.t("widget.styling.radius")}: {borderRadius()}px</label>
              <input
                type="range"
                min="0"
                max="24"
                value={borderRadius()}
                onInput={(e) => setBorderRadius(Number(e.currentTarget.value))}
                class="w-full h-2 bg-canvas-subtle rounded-lg appearance-none cursor-pointer accent-accent"
              />
            </div>

            {/* Shadow Intensity */}
            <div class="space-y-2">
              <label class="text-xs text-ink-muted">{i18n.t("widget.styling.shadow")}: {shadowIntensity()}%</label>
              <input
                type="range"
                min="0"
                max="50"
                value={shadowIntensity()}
                onInput={(e) => setShadowIntensity(Number(e.currentTarget.value))}
                class="w-full h-2 bg-canvas-subtle rounded-lg appearance-none cursor-pointer accent-accent"
              />
            </div>

            {/* Button Text (for button/modal/floating types) */}
            <Show when={selectedType() === "button" || selectedType() === "modal" || selectedType() === "floating"}>
              <div class="space-y-2">
                <label class="text-xs text-ink-muted">{i18n.t("widget.styling.buttonText")}</label>
                <Input
                  value={buttonText()}
                  onInput={(e) => setButtonText(e.currentTarget.value)}
                  placeholder={i18n.t("widget.button.text")}
                />
              </div>
            </Show>

            {/* Position (for floating type) */}
            <Show when={selectedType() === "floating"}>
              <div class="space-y-2">
                <label class="text-xs text-ink-muted">{i18n.t("widget.styling.position")}</label>
                <div class="grid grid-cols-2 gap-2">
                  {[
                    { value: "top-left", label: i18n.t("widget.position.topLeft") },
                    { value: "top-right", label: i18n.t("widget.position.topRight") },
                    { value: "bottom-left", label: i18n.t("widget.position.bottomLeft") },
                    { value: "bottom-right", label: i18n.t("widget.position.bottomRight") },
                  ].map((pos) => (
                    <button
                      class={`px-3 py-2 rounded-button text-xs font-medium transition-all ${
                        selectedPosition() === pos.value
                          ? "bg-accent text-white"
                          : "bg-canvas-subtle text-ink-muted hover:text-ink"
                      }`}
                      onClick={() => setSelectedPosition(pos.value as WidgetPosition)}
                    >
                      {pos.label}
                    </button>
                  ))}
                </div>
              </div>
            </Show>
          </div>

          <Show when={selectedType() === "map"}>
            <div class="space-y-5 pt-5 border-t border-border">
              <div class="flex items-center gap-2">
                <MapIcon />
                <div>
                  <label class="text-sm font-medium text-ink">Location map</label>
                  <p class="text-xs text-ink-muted">Paste a Google Maps/Mapy.cz link, coordinates, or full address.</p>
                </div>
              </div>

              <div class="grid gap-3 md:grid-cols-[1fr_auto] md:items-end">
                <Input
                  label="Real location"
                  value={mapLocationInput()}
                  onInput={(e) => setMapLocationInput(e.currentTarget.value)}
                  placeholder="Narodni 1, Prague or 50.0755, 14.4378"
                />
                <Button
                  type="button"
                  isLoading={resolvingMap()}
                  onClick={() => void resolveMapLocation()}
                  class="md:mb-[1.625rem]"
                >
                  Find location
                </Button>
              </div>

              <Show when={mapMessage()}>
                <p class={`text-sm ${mapMessage()?.startsWith("Resolved") || mapMessage() === "Location resolved." ? "text-success" : "text-error"}`}>
                  {mapMessage()}
                </p>
              </Show>

              <div class="grid gap-4 md:grid-cols-2">
                <Select
                  label="Map style"
                  value={mapStyle()}
                  onChange={(value) => setMapStyle(value)}
                  options={MAP_STYLE_OPTIONS}
                />
                <div class="space-y-2">
                  <label class="block font-display text-sm font-medium text-ink">Marker color</label>
                  <div class="flex items-center gap-3">
                    <input
                      type="color"
                      value={mapMarkerColor()}
                      onInput={(e) => setMapMarkerColor(e.currentTarget.value)}
                      class="h-11 w-12 rounded-button border border-border bg-canvas cursor-pointer"
                    />
                    <Input
                      value={mapMarkerColor()}
                      onInput={(e) => setMapMarkerColor(e.currentTarget.value)}
                      placeholder="#a65c3e"
                    />
                  </div>
                </div>
              </div>

              <Show when={mapStyle() === "custom"}>
                <Input
                  label="Custom tile URL"
                  value={customTileUrl()}
                  onInput={(e) => setCustomTileUrl(e.currentTarget.value)}
                  placeholder="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                  hint="Use a Leaflet-compatible tile URL with {z}, {x}, and {y}."
                />
              </Show>

              <div class="grid gap-4 md:grid-cols-2">
                <div class="space-y-2">
                  <label class="text-xs text-ink-muted">Zoom: {mapZoom()}</label>
                  <input
                    type="range"
                    min="3"
                    max="19"
                    value={mapZoom()}
                    onInput={(e) => setMapZoom(Number(e.currentTarget.value))}
                    class="w-full h-2 bg-canvas-subtle rounded-lg appearance-none cursor-pointer accent-accent"
                  />
                </div>
                <div class="space-y-2">
                  <label class="text-xs text-ink-muted">Height: {mapHeight()}px</label>
                  <input
                    type="range"
                    min="260"
                    max="620"
                    step="20"
                    value={mapHeight()}
                    onInput={(e) => setMapHeight(Number(e.currentTarget.value))}
                    class="w-full h-2 bg-canvas-subtle rounded-lg appearance-none cursor-pointer accent-accent"
                  />
                </div>
              </div>

              <Show when={showPreview()}>
                <div class="rounded-card border border-border bg-canvas p-3">
                  <LocationMap
                    coordinates={mapCoordinates()}
                    mapStyle={mapStyle()}
                    customTileUrl={customTileUrl()}
                    markerColor={mapMarkerColor()}
                    markerLabel={props.config.tenantName}
                    height={mapHeight()}
                    zoom={mapZoom()}
                  />
                  <div class="mt-3 flex flex-wrap items-center justify-between gap-2 text-xs text-ink-muted">
                    <span>{activeMapTileStyle().name}</span>
                    <span>{mapCoordinates().latitude.toFixed(5)}, {mapCoordinates().longitude.toFixed(5)}</span>
                  </div>
                </div>
              </Show>
            </div>
          </Show>

          {/* Live Preview Toggle */}
          <div class="pt-4 border-t border-border">
            <button
              class="flex items-center gap-2 text-sm text-ink-muted hover:text-ink transition-colors"
              onClick={() => setShowPreview(!showPreview())}
            >
              <EyeIcon />
              {showPreview() ? i18n.t("widget.preview.hide") : i18n.t("widget.preview.show")}
            </button>
          </div>
        </CardContent>
      </Card>

      {/* Code Snippets */}
      <Card class="surface-elevated">
        <CardHeader>
          <div class="flex items-center justify-between">
            <div>
              <CardTitle class="text-lg flex items-center gap-2">
                <CodeIcon />
                {i18n.t("widget.code.title")}
              </CardTitle>
              <CardDescription>{i18n.t("widget.code.desc")}</CardDescription>
            </div>
            <Badge variant="secondary" class="text-xs">
              ID: {widgetId()}
            </Badge>
          </div>
        </CardHeader>
        <CardContent>
          <Show when={copyError()}>
            <div class="mb-4 p-3 rounded-xl bg-[hsl(var(--error-soft))] border border-[hsl(var(--error))/20] text-[hsl(var(--error))] text-sm font-medium animate-fade-in">
              {copyError()}
            </div>
          </Show>
          <Tabs defaultValue="html">
            <TabsList class="mb-4 flex-wrap">
              <TabsTrigger value="html">HTML</TabsTrigger>
              <TabsTrigger value="react">React</TabsTrigger>
              <TabsTrigger value="vue">Vue</TabsTrigger>
              <TabsTrigger value="js">JS</TabsTrigger>
              <TabsTrigger value="php">PHP</TabsTrigger>
              <TabsTrigger value="solid">SolidJS</TabsTrigger>
              <TabsTrigger value="astro">Astro</TabsTrigger>
              <TabsTrigger value="ts">TypeScript</TabsTrigger>
              <TabsTrigger value="angular">Angular</TabsTrigger>
              <TabsTrigger value="svelte">Svelte</TabsTrigger>
            </TabsList>

            <TabsContent value="html">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().html}</code></pre>
                <Tooltip content={copiedSnippet() === "html" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().html, "html")}
                  >
                    {copiedSnippet() === "html" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>

            <TabsContent value="react">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().react}</code></pre>
                <Tooltip content={copiedSnippet() === "react" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().react, "react")}
                  >
                    {copiedSnippet() === "react" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>

            <TabsContent value="vue">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().vue}</code></pre>
                <Tooltip content={copiedSnippet() === "vue" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().vue, "vue")}
                  >
                    {copiedSnippet() === "vue" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>

            <TabsContent value="js">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().js}</code></pre>
                <Tooltip content={copiedSnippet() === "js" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().js, "js")}
                  >
                    {copiedSnippet() === "js" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>

            <TabsContent value="php">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().php}</code></pre>
                <Tooltip content={copiedSnippet() === "php" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().php, "php")}
                  >
                    {copiedSnippet() === "php" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>

            <TabsContent value="solid">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().solid}</code></pre>
                <Tooltip content={copiedSnippet() === "solid" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().solid, "solid")}
                  >
                    {copiedSnippet() === "solid" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>

            <TabsContent value="astro">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().astro}</code></pre>
                <Tooltip content={copiedSnippet() === "astro" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().astro, "astro")}
                  >
                    {copiedSnippet() === "astro" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>

            <TabsContent value="ts">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().ts}</code></pre>
                <Tooltip content={copiedSnippet() === "ts" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().ts, "ts")}
                  >
                    {copiedSnippet() === "ts" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>

            <TabsContent value="angular">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().angular}</code></pre>
                <Tooltip content={copiedSnippet() === "angular" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().angular, "angular")}
                  >
                    {copiedSnippet() === "angular" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>

            <TabsContent value="svelte">
              <div class="relative">
                <pre class="overflow-x-auto rounded-card border border-border bg-ink p-4 text-xs text-canvas"><code>{currentCode().svelte}</code></pre>
                <Tooltip content={copiedSnippet() === "svelte" ? i18n.t("common.copied") : i18n.t("common.copy")}>
                  <Button
                    size="sm"
                    variant="secondary"
                    class="absolute top-3 right-3"
                    onClick={() => copyToClipboard(currentCode().svelte, "svelte")}
                  >
                    {copiedSnippet() === "svelte" ? <CheckIcon /> : <CopyIcon />}
                  </Button>
                </Tooltip>
              </div>
            </TabsContent>
          </Tabs>

          <div class="mt-6 p-4 rounded-card bg-accent/5 border border-accent/10">
            <div class="flex items-start gap-3">
              <BookraCharacter pose="hello" size="sm" animate={false} />
              <div class="text-sm">
                <p class="font-medium text-ink">{i18n.t("widget.install.title")}</p>
                <p class="text-ink-muted mt-1">{i18n.t("widget.install.desc")}</p>
                <a 
                  href={props.config.publicBookingUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  class="inline-flex items-center gap-1 text-accent hover:text-accent/80 font-medium mt-2 transition-colors"
                >
                  {i18n.t("widget.install.preview")}
                  <ExternalLinkIcon />
                </a>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Security Note */}
      <Card class="surface-elevated border-warning/30 bg-warning/5">
        <CardContent class="py-4">
          <div class="flex items-start gap-3">
            <div class="text-warning"><LockIcon /></div>
            <div class="text-sm">
              <p class="font-medium text-ink">{i18n.t("widget.security.title")}</p>
              <p class="text-ink-muted mt-1">{i18n.t("widget.security.desc")}</p>
              <ul class="mt-2 space-y-1 text-ink-muted list-disc list-inside">
                <li>{i18n.t("widget.security.https")}</li>
                <li>{i18n.t("widget.security.isolation")}</li>
                <li>{i18n.t("widget.security.cors")}</li>
              </ul>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
