const { useState, useEffect } = React;

const DEFAULTS = window.CITY_DEFAULTS;

const LABELS = {
  en: {
    planTrip: "Plan Your Trip",
    destinations: "Destinations",
    addCity: "Add another city",
    remove: "Remove",
    requestProposal: "Request Proposal",
    reviewProposal: "Review & Submit Proposal",
    summaryPanel: "Budget Summary",
    budgetBox: "Total Trip Budget",
    perDay: "Per Day",
    breakdown: "Breakdown by Category",
    accommodation: "Accommodation",
    transportation: "Transportation",
    food: "Food & Dining",
    extras: "Gifts & Extras",
    city: "City",
    days: "Days",
    dailyCost: "Daily Cost",
    cityTotal: "City Total",
    detailsPerCity: "Details per City",
    totalBudget: "Total Budget",
    perDayAverage: "Per Day Average",
    tripOverview: "Trip Overview",
    tripDuration: "Trip Duration",
    citiesVisited: "Cities Visited",
    downloadHTML: "Download HTML Report",
    downloadPDF: "Download PDF Report",
    shareEmail: "Share via Email",
    shareWhatsApp: "Share on WhatsApp",
    shareTwitter: "Share on Twitter",
    shareFacebook: "Share on Facebook",
    confirmSend: "Confirm & Send Email",
    cancel: "Cancel",
    email: "Email Address",
    phone: "Phone Number",
    fullName: "Full Name",
    birthDate: "Birth Date",
    passportNumber: "Passport Number",
    wiseaccount: "WISE account IBAN EUR",
    personalID: "Personal ID / National ID",
    issueDate: "Issue Date",
    expiryDate: "Expiry Date",
    issuingAuthority: "Issuing Authority",
    mealsOptions: "My meal options for this period are:",
    accommodationType: "Accommodation Type",
    stars: "Stars",
    spendAmount: "Amount of Money",
    attractions: "Paid Attractions",
    safetyBuffer: "Consider adding",
    safetyBufferRest: "as a safety buffer for unexpected expenses.",
    withBuffer: "Total with Buffer"
  },
  pt: {
    planTrip: "Planeje Sua Viagem",
    destinations: "Destinos",
    addCity: "Adicionar outra cidade",
    remove: "Remover",
    requestProposal: "Solicitar Proposta",
    reviewProposal: "Revisar e Enviar Proposta",
    summaryPanel: "Resumo do Orçamento",
    budgetBox: "Orçamento Total da Viagem",
    perDay: "Por Dia",
    breakdown: "Distribuição por Categoria",
    accommodation: "Acomodação",
    transportation: "Transporte",
    food: "Alimentação",
    extras: "Presentes & Extras",
    city: "Cidade",
    days: "Dias",
    dailyCost: "Custo Diário",
    cityTotal: "Total da Cidade",
    detailsPerCity: "Detalhes por Cidade",
    totalBudget: "Orçamento Total",
    perDayAverage: "Média por Dia",
    tripOverview: "Visão Geral da Viagem",
    tripDuration: "Duração da Viagem",
    citiesVisited: "Cidades Visitadas",
    downloadHTML: "Baixar Relatório HTML",
    downloadPDF: "Baixar Relatório PDF",
    shareEmail: "Compartilhar por Email",
    shareWhatsApp: "Compartilhar no WhatsApp",
    shareTwitter: "Compartilhar no Twitter",
    shareFacebook: "Compartilhar no Facebook",
    confirmSend: "Confirmar e Enviar E-mail",
    cancel: "Cancelar",
    email: "E-mail",
    phone: "Telefone",
    fullName: "Nome Completo",
    birthDate: "Data de Nascimento",
    passportNumber: "Número do Passaporte",
    wiseaccount: "IBAN da conta WISE em EURO",
    personalID: "Identidade / CPF",
    issueDate: "Data de Emissão",
    expiryDate: "Data de Validade",
    issuingAuthority: "Órgão Emissor",
    mealsOptions: "Minhas opções de refeição para esse período:",
    accommodationType: "Tipo de Acomodação",
    stars: "Estrelas",
    spendAmount: "Valor de Gastos",
    attractions: "Atrações Pagas",
    safetyBuffer: "Considere adicionar",
    safetyBufferRest: "como reserva para imprevistos.",
    withBuffer: "Total com Reserva"
  }
};

const transportOptionsByLang = {
  en: [
    { label: "Flight ✈️", value: "Flight", icon: "✈️" },
    { label: "Train 🚆", value: "Train", icon: "🚆" },
    { label: "Bus 🚌", value: "Bus", icon: "🚌" },
    { label: "Car 🚗", value: "Car", icon: "🚗" },
    { label: "Boat ⛴️", value: "Boat", icon: "⛴️" }
  ],
  pt: [
    { label: "Voo ✈️", value: "Flight", icon: "✈️" },
    { label: "Trem 🚆", value: "Train", icon: "🚆" },
    { label: "Ônibus 🚌", value: "Bus", icon: "🚌" },
    { label: "Carro 🚗", value: "Car", icon: "🚗" },
    { label: "Barco ⛴️", value: "Boat", icon: "⛴️" }
  ]
};

const transportPriceOptionsByLang = {
  en: [
    { label: "very cheap", value: "very cheap" },
    { label: "cheap", value: "cheap" },
    { label: "average", value: "average" },
    { label: "expensive", value: "expensive" },
    { label: "very expensive", value: "very expensive" }
  ],
  pt: [
    { label: "muito barato", value: "very cheap" },
    { label: "barato", value: "cheap" },
    { label: "médio", value: "average" },
    { label: "caro", value: "expensive" },
    { label: "muito caro", value: "very expensive" }
  ]
};

const foodOptionsByLang = {
  en: ["Breakfast", "Snack1", "Lunch", "Snack2", "Dinner", "Snack3"],
  pt: ["Café da manhã", "Lanche1", "Almoço", "Lanche2", "Jantar", "Lanche3"]
};

const starsOptionsByLang = {
  en: [
    { label: "1 star", value: "1" },
    { label: "2 stars", value: "2" },
    { label: "3 stars", value: "3" },
    { label: "4 stars", value: "4" },
    { label: "5 stars", value: "5" }
  ],
  pt: [
    { label: "1 estrela", value: "1" },
    { label: "2 estrelas", value: "2" },
    { label: "3 estrelas", value: "3" },
    { label: "4 estrelas", value: "4" },
    { label: "5 estrelas", value: "5" }
  ]
};

const accomOptionsByLang = {
  en: ["Hotel", "Hostel", "Airbnb", "Own lodge", "Others"],
  pt: ["Hotel", "Hostel", "Airbnb", "Próprio", "Outros"]
};

const spendOptionsByLang = {
  en: [
    { label: "No spend", value: "No spend" },
    { label: "very small", value: "Very Small" },
    { label: "small", value: "Small" },
    { label: "average", value: "Average" },
    { label: "high", value: "High" },
    { label: "very high", value: "Very High" }
  ],
  pt: [
    { label: "Nada", value: "No spend" },
    { label: "muito pouco", value: "Very Small" },
    { label: "pouco", value: "Small" },
    { label: "mais ou menos", value: "Average" },
    { label: "muito", value: "High" },
    { label: "muitíssimo", value: "Very High" }
  ]
};

const attractionsOptionsByLang = {
  en: [
    { label: "0", value: "0" }, { label: "1", value: "1" }, { label: "2", value: "2" }, { label: "3", value: "3" },
    { label: "4", value: "4" }, { label: "5", value: "5" }, { label: "6", value: "6" }, { label: "7", value: "7" },
    { label: "8", value: "8" }, { label: "9", value: "9" }, { label: "10", value: "10" }, { label: ">10", value: ">10" }
  ],
  pt: [
    { label: "0", value: "0" }, { label: "1", value: "1" }, { label: "2", value: "2" }, { label: "3", value: "3" },
    { label: "4", value: "4" }, { label: "5", value: "5" }, { label: "6", value: "6" }, { label: "7", value: "7" },
    { label: "8", value: "8" }, { label: "9", value: "9" }, { label: "10", value: "10" }, { label: ">10", value: ">10" }
  ]
};

function lookupMetric(cityRaw, metric) {
  if (!cityRaw) return DEFAULTS && DEFAULTS[metric] ? DEFAULTS[metric] : {};
  
  const canon = v => v ? v.normalize("NFD").replace(/[\u0300-\u036f]/g, "").trim().toLowerCase() : "";
  const inputCanon = canon(cityRaw);
  
  // First, try to find it as a city
  const cityKey = Object.keys(window.CITY_MAPPING || {}).find(c => canon(c) === inputCanon);
  
  let country, level;
  
  if (!cityKey) {
    // If not found as a city, check if it's a country name
    const countryKey = Object.keys(window.COUNTRY_TIERS || {}).find(c => canon(c) === inputCanon);
    
    if (countryKey) {
      // User entered a country name
      country = countryKey;
      level = "medium";  // Default level for countries
    } else {
      // Not found as city or country, use defaults
      return DEFAULTS && DEFAULTS[metric] ? DEFAULTS[metric] : {};
    }
  } else {
    // Found as a city
    const cityData = window.CITY_MAPPING[cityKey];
    country = cityData.country;
    level = cityData.level;
  }
  
  const tier = window.COUNTRY_TIERS[country];
  if (!tier || !window.BUDGET_TIERS[tier]) {
    return DEFAULTS && DEFAULTS[metric] ? DEFAULTS[metric] : {};
  }
  
  const basePrices = window.BUDGET_TIERS[tier][metric];
  if (!basePrices) {
    return DEFAULTS && DEFAULTS[metric] ? DEFAULTS[metric] : {};
  }
  
  const multiplier = window.COST_MULTIPLIERS[level] || 1.0;
  
  const adjustedPrices = {};
  if (metric === "MEAL_PRICES" || metric === "SPEND_LEVELS" || metric === "ATTRACTION_PRICES") {
    Object.keys(basePrices).forEach(key => {
      adjustedPrices[key] = Math.round(basePrices[key] * multiplier);
    });
  } else if (metric === "HOTEL_PRICES") {
    Object.keys(basePrices).forEach(accomType => {
      adjustedPrices[accomType] = {};
      Object.keys(basePrices[accomType]).forEach(stars => {
        adjustedPrices[accomType][stars] = Math.round(basePrices[accomType][stars] * multiplier);
      });
    });
  }
  
  return adjustedPrices;
}


function diffDays(start, end) {
  if (!start || !end) return 1;
  const a = new Date(start), b = new Date(end);
  const ms = (b - a);
  return Math.max(1, Math.round(ms/(1000*60*60*24)));
}

async function calculateCityTotalsByCategory(city, idx, cities) {
  const meals = lookupMetric(city.city, "MEAL_PRICES");
  const accoms = lookupMetric(city.city, "HOTEL_PRICES");
  const spends = lookupMetric(city.city, "SPEND_LEVELS");
  const atts = lookupMetric(city.city, "ATTRACTION_PRICES");

  const accom = city.accomType && city.stars && accoms[city.accomType]
    ? (accoms[city.accomType][city.stars] || 0)
    : 0;

  let transport = 0;
  if (idx > 0 && city.transport && cities[idx-1].city && city.city) {
    const prevCityName = cities[idx-1].city;
    const currentCityName = city.city;
    
    let prevCoords = window.GEOCODE_CACHE[prevCityName];
    let currentCoords = window.GEOCODE_CACHE[currentCityName];
    
    if (!prevCoords && window.geocodeCity) {
      prevCoords = await window.geocodeCity(prevCityName);
      if (prevCoords) window.GEOCODE_CACHE[prevCityName] = prevCoords;
    }
    
    if (!currentCoords && window.geocodeCity) {
      currentCoords = await window.geocodeCity(currentCityName);
      if (currentCoords) window.GEOCODE_CACHE[currentCityName] = currentCoords;
    }
    
    if (prevCoords && currentCoords) {
      const distance = window.calculateDistance(
        prevCoords.lat, prevCoords.lon,
        currentCoords.lat, currentCoords.lon
      );
      
      const cityData = window.CITY_MAPPING[city.city];
      const tier = cityData && cityData.country ? 
        (window.COUNTRY_TIERS[cityData.country] || "Medium") : "Medium";
      
      const rates = window.TRANSPORT_RATES[tier] || window.TRANSPORT_RATES["Medium"];
      const rate = rates ? rates[city.transport] : undefined;
      
      if (rate) {
        transport = rate.base + (distance * rate.perKm);
        if (city.transportPrice && window.TRANSPORT_COST_MULTIPLIERS[city.transportPrice]) {
          transport *= window.TRANSPORT_COST_MULTIPLIERS[city.transportPrice];
        }
      }
    }
  }

  let food = 0;
  Object.keys(meals).forEach(meal => {
    if (city.foodChecks && city.foodChecks[meal]) food += meals[meal] || 0;
  });

  const extras = (city.spend ? (spends[city.spend] || 0) : 0) + (city.attractions ? (atts[city.attractions] || 0) : 0);

  return { accommodation: accom, transport, food, extras };
}

async function sumTotalsByCategory(cities) {
  const results = await Promise.all(
    cities.map((city, idx) => calculateCityTotalsByCategory(city, idx, cities))
  );
  
  return results.reduce((agg, curr) => ({
    accommodation: agg.accommodation + curr.accommodation,
    transport: agg.transport + curr.transport,
    food: agg.food + curr.food,
    extras: agg.extras + curr.extras
  }), {accommodation:0, transport:0, food:0, extras:0});
}

async function calculateCityTotal(city, idx, cities) {
  const cat = await calculateCityTotalsByCategory(city, idx, cities);
  return cat.accommodation + cat.transport + cat.food + cat.extras;
}

function generateReport(cities, cityTotals, tripTotal, tripDays, startDate, endDate, totalsCat) {
  const reportHTML = `
    <html>
      <head>
        <style>
          html, body { margin: 0 !important; padding: 0 !important; }
          body { font-family: Arial, sans-serif; padding: 5px 15px !important; color: #333; }
          .header { text-align: center; margin-bottom: 15px; margin-top: 0; }
          .header h1 { margin: 0; color: #0a84ff; font-size: 24px; }
          .header p { margin: 3px 0 0 0; font-size: 12px; }
          .section { margin-bottom: 20px; page-break-inside: avoid; }
          .section-title { font-weight: bold; font-size: 14px; border-bottom: 2px solid #0a84ff; padding-bottom: 6px; margin-bottom: 10px; color: #ffffff;}
          table { width: 100%; border-collapse: collapse; margin-top: 8px; font-size: 11px; }
          th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
          th { background-color: #0a84ff; color: white; }
          tr:nth-child(even) { background-color: #f9f9f9; }
          .summary-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 8px; }
          .summary-box { padding: 10px; background-color: #f0f7ff; border-left: 3px solid #0a84ff; font-size: 12px; }
          .summary-box strong { display: block; font-size: 16px; color: #0a84ff; }
          .breakdown { margin-top: 8px; font-size: 12px; }
          .breakdown-item { display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px dashed #ddd; }
          .breakdown-item:last-child { border-bottom: none; }
          .total { font-size: 18px; font-weight: bold; color: #0a84ff; margin-top: 15px; text-align: right; }
          h3 { margin-top: 15px; margin-bottom: 8px; font-size: 13px; }
        </style>
      </head>
      <body>
        <div class="header">
          <h1>Trip Budget Report</h1>
          <p>${startDate ? new Date(startDate).toLocaleDateString() : "--"} to ${endDate ? new Date(endDate).toLocaleDateString() : "--"}</p>
        </div>

        <div class="section">
          <div class="section-title">Trip Overview</div>
          <div class="summary-grid">
            <div class="summary-box">
              <strong>${tripTotal.toFixed(2)}€</strong>
              Total Budget
            </div>
            <div class="summary-box">
              <strong>${(tripTotal/tripDays).toFixed(2)}€/day</strong>
              Per Day Average
            </div>
            <div class="summary-box">
              <strong>${tripDays} days</strong>
              Trip Duration
            </div>
            <div class="summary-box">
              <strong>${cities.length}</strong>
              Cities Visited
            </div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">Budget Breakdown by Category</div>
          <div class="breakdown">
            <div class="breakdown-item">
              <span>🏨 Accommodation</span>
              <strong>${totalsCat.accommodation.toFixed(2)}€</strong>
            </div>
            <div class="breakdown-item">
              <span>💰 transportation</span>
              <strong>${totalsCat.transport.toFixed(2)}€</strong>
            </div>
            <div class="breakdown-item">
              <span>🍽️ Food & Dining</span>
              <strong>${totalsCat.food.toFixed(2)}€</strong>
            </div>
            <div class="breakdown-item">
              <span>🎁 Gifts & Extras</span>
              <strong>${totalsCat.extras.toFixed(2)}€</strong>
            </div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">Cities & Daily Breakdown</div>
          <table>
            <thead>
              <tr>
                <th>City</th>
                <th>Days</th>
                <th>Daily Cost</th>
                <th>City Total</th>
              </tr>
            </thead>
            <tbody>
              ${cities.map((city, idx) => {
                const days = city.startDate && city.endDate ? Math.max(1, Math.round((new Date(city.endDate) - new Date(city.startDate))/(1000*60*60*24))) : 1;
                const total = cityTotals[idx] || 0;
                const daily = days ? (total/days).toFixed(2) : total.toFixed(2);
                return `
                <tr>
                  <td>${city.city}</td>
                  <td>${days}</td>
                  <td>${daily}€</td>
                  <td><strong>${total.toFixed(2)}€</strong></td>
                </tr>
              `;
              }).join('')}
            </tbody>
          </table>
        </div>

        <div class="section">
          <div class="section-title">Details per City</div>
          ${cities.map((city, idx) => `
            <div style="margin-bottom: 20px; page-break-inside: avoid;">
              <h3>${city.city}</h3>
              <table style="font-size: 11px;">
                <tr>
                  <td><strong>Dates:</strong> ${city.startDate} to ${city.endDate}</td>
                  <td><strong>Accommodation:</strong> ${city.stars}★ ${city.accomType}</td>
                </tr>
                <tr>
                  <td><strong>Transport:</strong> ${city.transport} (${city.transportPrice})</td>
                  <td><strong>Spending:</strong> ${city.spend}</td>
                </tr>
              </table>
            </div>
          `).join('')}
        </div>

        <div class="total">
          Total Trip Budget: €${tripTotal.toFixed(2)}
        </div>
      </body>
    </html>
  `;

  return reportHTML;
}


function transportIcon(transportType) {
  const icons = {
    "Flight": "✈️",
    "Train": "🚆", 
    "Bus": "🚌",
    "Car": "🚗",
    "Boat": "⛴️"
  };
  return icons[transportType] || "➡️";
}
function TripPlannerApp() {
    const [cities, setCities] = useState([
  { 
    city: "", startDate: "", endDate: "", transport: "", transportPrice: "",
    foodChecks: {}, stars: "", accomType: "", spend: "", attractions: ""
  }
]);

  const [language, setLanguage] = useState('en');
  const transportOptions = transportOptionsByLang[language];
  const transportPriceOptions = transportPriceOptionsByLang[language];
  const foodOptions = foodOptionsByLang[language];
  const starsOptions = starsOptionsByLang[language];
  const accomOptions = accomOptionsByLang[language];
  const spendOptions = spendOptionsByLang[language];
  const attractionsOptions = attractionsOptionsByLang[language];
  const [submitted, setSubmitted] = useState(false);
  const [filteredCities, setFilteredCities] = useState([]);
  const [cityTotals, setCityTotals] = useState([]);
  const [totalsCat, setTotalsCat] = useState({accommodation:0, transport:0, food:0, extras:0});
  const [showProposalForm, setShowProposalForm] = useState(false);
  const [proposalData, setProposalData] = useState({
    email: '',
    phone: '',
    fullName: '',
    passportNumber: '',
    issueDate: '',
    expiryDate: '',
    issuingAuthority: '',
    personalID: '',
    birthDate: '',
    wiseaccount: '',
  });
  const [showReviewModal, setShowReviewModal] = useState(false);
  const [reportHTML, setReportHTML] = useState('');
  
  const [currency, setCurrency] = useState('EUR'); // Add this line

// Add these new state variables in TripPlannerApp component, after existing useState declarations:
const [showBudgetBubble, setShowBudgetBubble] = useState(false);
const [bubblePosition, setBubblePosition] = useState({ x: 50, y: 100 });

// Add this useEffect to detect when total budget card is visible (runs after calculations)
useEffect(() => {
  const checkBudgetCard = () => {
    if (tripTotal > 0) {
      const budgetBox = document.querySelector('.budget-box');
      if (budgetBox) {
        const rect = budgetBox.getBoundingClientRect();
        const isVisible = rect.top < window.innerHeight && rect.bottom > 0;
        setShowBudgetBubble(!isVisible);
      } else {
        setShowBudgetBubble(true);
      }
    }
  };

  checkBudgetCard();
  window.addEventListener('scroll', checkBudgetCard);
  window.addEventListener('resize', checkBudgetCard);
  
  return () => {
    window.removeEventListener('scroll', checkBudgetCard);
    window.removeEventListener('resize', checkBudgetCard);
  };
}, [tripTotal, cities]);


  const allCities = Object.keys(window.CITY_MAPPING || {}).sort();

  useEffect(() => {
    async function calc() {
      const totals = await Promise.all(
        cities.map((city, idx) => calculateCityTotal(city, idx, cities))
      );
      setCityTotals(totals);
      
      const catTotals = await sumTotalsByCategory(cities);
      setTotalsCat(catTotals);
    }
    calc();
  }, [cities]);

  const handleCityChange = (idx, field, value) => {
    const updated = [...cities];
    updated[idx][field] = value;
    setCities(updated);
    setSubmitted(false);
    
    if (field === "city" && value && value.length >= 1) {
      const filtered = allCities.filter(city => 
        city.toLowerCase().startsWith(value.toLowerCase())
      );
      setFilteredCities(filtered);
    } else {
      setFilteredCities([]);
    }
  };

  const handleFoodCheck = (idx, meal) => {
  const updated = [...cities];
  // Map PT display names to English storage keys
  const englishKey = meal === "Café da manhã" ? "Breakfast" :
                    meal === "Lanche1" ? "Snack1" :
                    meal === "Almoço" ? "Lunch" :
                    meal === "Lanche2" ? "Snack2" :
                    meal === "Jantar" ? "Dinner" :
                    meal === "Lanche3" ? "Snack3" : meal;
  updated[idx].foodChecks = {...(updated[idx].foodChecks||{}), [englishKey]: !updated[idx]?.foodChecks?.[englishKey]};
  setCities(updated);
  setSubmitted(false);
};

// Add this function near the top with other helper functions
function formatCurrency(amount, currency) {
  const rate = currency === 'BRL' ? 6.2 : 1; // EUR to BRL ≈ 6.2 (update as needed)
  const converted = amount * rate;
  const symbol = currency === 'BRL' ? 'R$ ' : '€';
  return symbol + converted.toLocaleString('pt-BR', { 
    minimumFractionDigits: 2, 
    maximumFractionDigits: 2 
  });
}


  const addCity = () => {
    setCities([...cities, { city: "", startDate: "", endDate: "", transport: "", transportPrice: "", foodChecks: {}, stars: "", accomType: "", spend: "", attractions: "" }]);
    setSubmitted(false);
  };

  const removeCity = (idx) => {
    if (cities.length === 1) return;
    setCities(cities.filter((_, i) => i !== idx));
    setSubmitted(false);
  };

  const calculate = e => {
    e.preventDefault();
    setSubmitted(true);
  };

  const resetAll = () => {
    setCities([{ city: "", startDate: "", endDate: "", transport: "", transportPrice: "", foodChecks: {}, stars: "", accomType: "", spend: "", attractions: "" }]);
    setSubmitted(false);
    setFilteredCities([]);
  };

  const getCityDays = (city) => city.startDate && city.endDate ? diffDays(city.startDate, city.endDate) : 1;

  const startDate = cities[0]?.startDate || "";
  const endDate = cities.length > 0 ? cities[cities.length-1].endDate : "";
  const tripDays = (startDate && endDate) ? diffDays(startDate, endDate) : 1;

  const cityDays = cities.map(getCityDays);
  const cityPerDay = cityTotals.map((total, i) => cityDays[i] ? (total/cityDays[i]) : total);
  const tripTotal = cityTotals.reduce((a,b) => a+b, 0);

  const breakdown = [
    { key:"accommodation", label:"Accommodation", icon:"🏨", className:"fill-accomod", value: totalsCat.accommodation },
    { key:"transportation", label:"Transportation", icon:"💰", className:"fill-transport", value: totalsCat.transport },
    { key:"food", label:"Food & Dining", icon:"🍽️", className:"fill-food", value: totalsCat.food },
    { key:"extras", label:"Gifts & Extras", icon:"🎁", className:"fill-extras", value: totalsCat.extras }
  ];
  const breakdownTotal = breakdown.reduce((a,b)=>a+b.value,0);
  const buffer = tripTotal * 0.15;

  const citiesToShow = filteredCities.length > 0 ? filteredCities : [];

  const handleProposalSubmit = (e) => {
    e.preventDefault();
    // Generate the HTML report
    const html = generateReport(cities, cityTotals, tripTotal, tripDays, startDate, endDate, totalsCat);
    setReportHTML(html);
    setShowReviewModal(true);
    setShowProposalForm(false);
  };
  
  

  const confirmAndSendEmail = () => {
  // Create hidden form for email submission
  const form = document.createElement('form');
  form.method = 'POST';
  form.action = 'https://formsubmit.co/contact@tunvolo.com';
  form.style.display = 'none';
  
  // Create hidden input for redirect URL
const redirectInput = document.createElement('input');
redirectInput.type = 'hidden';
redirectInput.name = '_next';  // This special field tells formsubmit.co the redirect URL

// Replace with your desired URL - e.g., your own website's thank-you page
redirectInput.value = 'https://tunvolo.com/tool/';

// Append it to the form
form.appendChild(redirectInput);
  
  // Add all proposal data
  Object.keys(proposalData).forEach(key => {
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = key;
    input.value = proposalData[key];
    form.appendChild(input);
  });
  
  // Create detailed trip summary with all budget info
  const tripSummary = `
=== TRIP BUDGET PROPOSAL ===

TRIP OVERVIEW:
- Dates: ${startDate ? new Date(startDate).toLocaleDateString() : '--'} to ${endDate ? new Date(endDate).toLocaleDateString() : '--'}
- Duration: ${tripDays} days
- Cities: ${cities.map(c => c.city).join(' → ')}
- Total Budget: €${tripTotal.toFixed(2)}
- Per Day Average: €${(tripTotal/tripDays).toFixed(2)}

BUDGET BREAKDOWN BY CATEGORY:
- 🏨 Accommodation: €${totalsCat.accommodation.toFixed(2)}
- 💰 Transportation: €${totalsCat.transport.toFixed(2)}
- 🍽️ Food & Dining: €${totalsCat.food.toFixed(2)}
- 🎁 Gifts & Extras: €${totalsCat.extras.toFixed(2)}

CITIES & DAILY BREAKDOWN:
${cities.map((city, idx) => {
  const days = city.startDate && city.endDate ? Math.max(1, Math.round((new Date(city.endDate) - new Date(city.startDate))/(1000*60*60*24))) : 1;
  const total = cityTotals[idx] || 0;
  const daily = days ? (total/days).toFixed(2) : total.toFixed(2);
  return `- ${city.city}: ${days} days | €${daily}/day | Total: €${total.toFixed(2)}`;
}).join('\n')}

DETAILS PER CITY:
${cities.map((city, idx) => `
${city.city}:
  Dates: ${city.startDate} to ${city.endDate}
  Accommodation: ${city.stars}★ ${city.accomType}
  Transport: ${city.transport} (${city.transportPrice})
  Meals: ${foodOptions.filter(f => city.foodChecks && city.foodChecks[f]).join(', ')}
  Spending Level: ${city.spend}
  Attractions: ${city.attractions}
`).join('\n')}

SAFETY BUFFER RECOMMENDATION:
- Suggested Buffer: €${buffer.toFixed(2)} (15%)
- Total with Buffer: €${(tripTotal + buffer).toFixed(2)}
  `;
  
  // Add trip summary
  const tripInput = document.createElement('input');
  tripInput.type = 'hidden';
  tripInput.name = 'trip_summary';
  tripInput.value = tripSummary;
  form.appendChild(tripInput);
  
  // Add subject
  const subjectInput = document.createElement('input');
  subjectInput.type = 'hidden';
  subjectInput.name = '_subject';
  subjectInput.value = `New Travel Proposal Request from ${proposalData.fullName}`;
  form.appendChild(subjectInput);
  
  // Add captcha disable
  const captchaInput = document.createElement('input');
  captchaInput.type = 'hidden';
  captchaInput.name = '_captcha';
  captchaInput.value = 'false';
  form.appendChild(captchaInput);
  
  document.body.appendChild(form);
  form.submit();
  
  setShowReviewModal(false);
  alert('Thank you! Your proposal has been sent successfully! We will contact you back as soon as possible.');
};

// Add this new draggable bubble component right before the return statement:
const BudgetBubble = () => {
  if (!showBudgetBubble || tripTotal === 0) return null;

  const handleMouseDown = (e) => {
    e.preventDefault();
    e.stopPropagation();

    const handleMouseMove = (moveEvent) => {
      const deltaX = moveEvent.clientX - startX;
      const deltaY = moveEvent.clientY - startY;
      setBubblePosition({
        x: Math.max(10, Math.min(startBubbleX + deltaX, window.innerWidth - 120)),
        y: Math.max(10, Math.min(startBubbleY + deltaY, window.innerHeight - 100))
      });
    };

    const handleMouseUp = () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
  };

  const handleTouchStart = (e) => {
    e.preventDefault();
    e.stopPropagation();

    const handleTouchMove = (moveEvent) => {
      const touch = moveEvent.touches[0];
      const deltaX = touch.clientX - startX;
      const deltaY = touch.clientY - startY;
      setBubblePosition({
        x: Math.max(10, Math.min(startBubbleX + deltaX, window.innerWidth - 120)),
        y: Math.max(10, Math.min(startBubbleY + deltaY, window.innerHeight - 100))
      });
    };

    const handleTouchEnd = () => {
      document.removeEventListener('touchmove', handleTouchMove);
      document.removeEventListener('touchend', handleTouchEnd);
    };

    document.addEventListener('touchmove', handleTouchMove, { passive: false });
    document.addEventListener('touchend', handleTouchEnd);
  };

  const currencySymbol = currency === 'BRL' ? 'R$' : '€';

  return (
    <div
      className="budget-bubble"
      style={{
        position: 'fixed',
        left: `${bubblePosition.x}px`,
        top: `${bubblePosition.y}px`,
        zIndex: 99999,
        width: '120px',  // Slightly wider for formatted numbers
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        color: 'white',
        padding: '10px 8px',
        borderRadius: '25px',
        boxShadow: '0 8px 25px rgba(102, 126, 234, 0.6)',
        fontSize: '11px',
        fontWeight: 'bold',
        textAlign: 'center',
        lineHeight: '1.1',
        cursor: 'move',
        userSelect: 'none',
        backdropFilter: 'blur(10px)',
        border: '2px solid rgba(255,255,255,0.3)',
        transform: 'translate(-50%, -50%)'
      }}
      onMouseDown={handleMouseDown}
      onTouchStart={handleTouchStart}
      title="Drag to move"
    >
      <div style={{ fontSize: '13px', marginBottom: '1px' }}>
        {formatCurrency(tripTotal, currency)}
      </div>
      <div style={{ fontSize: '9px', opacity: 0.9 }}>
        {formatCurrency(tripTotal/tripDays, currency)}/day
      </div>
    </div>
  );
};


  
  return (
    <>
    
     <BudgetBubble />
     
    <div className="selectors-container" style={{padding: '8px 0', background: 'transparent'}}>
  {/* Language Selector */}
  <div className="language-selector">
    <label className="label" style={{fontSize: '0.9em', display: 'block', marginBottom: '6px'}}>
      Choose your language
    </label>
    <div className="buttons" style={{display: 'flex', gap: '8px', justifyContent: 'center', flexWrap: 'wrap'}}>
      <button 
        type="button" 
        className={`language-chip ${language === 'en' ? 'active-en' : ''}`}
        onClick={() => setLanguage('en')}
        style={{padding: '8px 16px', fontSize: '0.9em'}}
      >
        English
      </button>
      <button 
        type="button" 
        className={`language-chip ${language === 'pt' ? 'active-pt' : ''}`}
        onClick={() => setLanguage('pt')}
        style={{padding: '8px 16px', fontSize: '0.9em'}}
      >
        Português (Brasil)
      </button>
    </div>
  </div>

  {/* Currency Selector */}
  <div className="currency-selector" style={{marginTop: '8px'}}>
    <label className="label" style={{fontSize: '0.85em', display: 'block', marginBottom: '4px', textAlign: 'center'}}>
      Currency
    </label>
    <div className="buttons" style={{display: 'flex', gap: '6px', justifyContent: 'center', flexWrap: 'wrap'}}>
      <button 
        type="button" 
        className={`language-chip ${currency === 'EUR' ? 'active-en' : ''}`}
        onClick={() => setCurrency('EUR')}
        style={{padding: '6px 12px', fontSize: '0.85em'}}
      >
        € EUR
      </button>
      <button 
        type="button" 
        className={`language-chip ${currency === 'BRL' ? 'active-pt' : ''}`}
        onClick={() => setCurrency('BRL')}
        style={{padding: '6px 12px', fontSize: '0.85em'}}
      >
        R$ BRL
      </button>
    </div>
  </div>
</div>






      <div className="card">
        <div className="header">
          <span style={{fontSize:"1.4em"}}>💲</span> {LABELS[language].planTrip}
        </div>
        <div className="section-title">{LABELS[language].destinations}</div>

        <form onSubmit={calculate} autoComplete="off">
          {cities.map((city, idx) => (
            <div className="city-section" key={idx}>
              {idx === 0 ? (
                <div className="city-phrase">
                  {language === "en" ? "I will stay in" : "Ficarei em"}&nbsp;
                  <input placeholder={LABELS[language].city} value={city.city} onChange={e => handleCityChange(idx, "city", e.target.value)} required list="city-suggestions" />
                  , {language === "en" ? "from" : "de"}
                  <input type="date" value={city.startDate} onChange={e => handleCityChange(idx, "startDate", e.target.value)} required />
                  {language === "en" ? "till" : "até"}
                  <input type="date" value={city.endDate} onChange={e => handleCityChange(idx, "endDate", e.target.value)} required />.
                  &nbsp;{LABELS[language].mealsOptions}
                </div>
              ) : (
                <div className="city-phrase">
                  {language === "en" ? "I am going to" : "Eu vou para"}&nbsp;
                  <input placeholder={LABELS[language].city} value={city.city} onChange={e => handleCityChange(idx, "city", e.target.value)} required style={{minWidth:85}} list="city-suggestions" />
                  &nbsp;{language === "en" ? "by" : "de"}
                  <select value={city.transport} required className="custom-select" onChange={e => handleCityChange(idx, "transport", e.target.value)} style={{margin: "0 8px"}}>
                    <option value="">{language === 'en' ? "Select Transportation..." : "Selecione Transporte..."}</option>
                    {transportOptions.map(opt => (
  <option value={opt.value} key={opt.value}>{opt.label}</option>
))}

                  </select>
                  <select value={city.transportPrice} required className="custom-select" onChange={e => handleCityChange(idx, "transportPrice", e.target.value)} style={{margin: "0 8px"}}>
                    <option value="">{language === 'en' ? "Price level..." : "Nível de preço..."}</option>
                    {transportPriceOptions.map(opt => (
  <option value={opt.value} key={opt.value}>{opt.label}</option>
))}

                  </select>
                  {language === "en" ? "and I will stay from" : "e ficarei de"}
                  <input type="date" value={city.startDate} onChange={e => handleCityChange(idx, "startDate", e.target.value)} required />
                  {language === "en" ? "till" : "até"}
                  <input type="date" value={city.endDate} onChange={e => handleCityChange(idx, "endDate", e.target.value)} required />.
                  &nbsp;{LABELS[language].mealsOptions}
                  <button className="remove-btn" type="button" onClick={() => removeCity(idx)} style={{marginLeft:"10px"}}>{LABELS[language].remove}</button>
                </div>
              )}
              <div className="food-checkbox-row">
                {foodOptions.map(meal => (
  <label key={meal}>
    <input
      type="checkbox"
     checked={!!city.foodChecks?.[
  meal === "Café da manhã" ? "Breakfast" :
  meal === "Lanche1" ? "Snack1" :
  meal === "Almoço" ? "Lunch" :
  meal === "Lanche2" ? "Snack2" :
  meal === "Jantar" ? "Dinner" :
  meal === "Lanche3" ? "Snack3" : meal
]}


      onChange={() => handleFoodCheck(idx, meal)}
    />
    {meal}
  </label>
))}

              </div>
              <div className="extra-phrase-row">
                {language === "en" ? "and I will stay in a" : "e vou me hospedar em"}
                <select value={city.accomType} required className="custom-select" onChange={e => handleCityChange(idx, "accomType", e.target.value)} >
                  <option value="">{language === "en" ? "Select accommodation..." : "Selecione acomodação..."}</option>
                  {accomOptions.map(opt => (
  <option key={opt} value={opt}>{opt}</option>
))}

                </select>
                <select value={city.stars} required className="custom-select" onChange={e => handleCityChange(idx, "stars", e.target.value)} >
                  <option value="">{language === "en" ? "Select stars..." : "Selecione estrelas..."}</option>
                  {starsOptions.map(opt => (
  <option key={opt.value} value={opt.value}>{opt.label}</option>
))}

                </select>
                 .
              </div>
              <div className="money-row">
                {language === "en" ? "I pretend to spend a" : "Pretendo gastar um"}
                <select value={city.spend} required className="custom-select" onChange={e => handleCityChange(idx, "spend", e.target.value)} >
                  <option value="">{language === "en" ? "Select amount..." : "Selecione valor..."}</option>
                  {spendOptions.map(opt => (
  <option key={opt.value} value={opt.value}>{opt.label}</option>
))}

                </select>
                {language === "en"
                  ? "amount of money during this period with gifts or any extras."
                  : "valor durante esse período em presentes ou extras."
                }
              </div>
              <div className="attractions-row">
                {language === "en" ? "Also, I am open to pay for at least" : "Também estou aberto a pagar por pelo menos"}
                <select value={city.attractions} required className="custom-select" onChange={e => handleCityChange(idx, "attractions", e.target.value)} >
                  <option value="">{language === "en" ? "Select number..." : "Selecione quantidade..."}</option>
                  {attractionsOptions.map(opt => (
  <option key={opt.value} value={opt.value}>{opt.label}</option>
))}

                </select>
                {language === 'en' ? "paid attractions." : "atrações pagas."}
              </div>
              <div className="city-days">
                {LABELS[language].days} in {LABELS[language].city.toLowerCase()}: {getCityDays(city)}
              </div>
              
              <div className="percity-day">
  {getCityDays(city) > 0 && cityTotals[idx] ? 
    `${LABELS[language].perDay}: ${formatCurrency(cityTotals[idx]/getCityDays(city), currency)}` : 
    ""
  }
</div>
              
              <div className="city-total">
  {LABELS[language].cityTotal}: {formatCurrency(cityTotals[idx] || 0, currency)}
</div>

            </div>
          ))}

         <button type="button" className="add-city-btn" onClick={addCity}>
  + {LABELS[language].addCity}
</button>
<datalist id="city-suggestions">
  {citiesToShow.map(cityName => (
    <option key={cityName} value={cityName} />
  ))}
</datalist>
        </form>
      </div>
      <div className="card summary-panel">
  <div className="summary-title">
    <span style={{fontSize:"1.2em",marginRight:7,background:"#39d48d",borderRadius:4,width:16,height:16,display:"inline-block"}}></span>
    {LABELS[language].summaryPanel}
  </div>

  <div style={{marginBottom:7,marginTop:3,padding:"4px 2px"}}>
    <div className="summary-row" style={{color:"#fff"}}>
      <span className="dest-icon">📅</span>
      <span>
        {startDate ? new Date(startDate).toLocaleDateString() : "--"} - {endDate ? new Date(endDate).toLocaleDateString() : "--"}
        {tripDays > 0 && (
          <span style={{color: "#7fff8d", marginLeft: 8, fontWeight:600, fontSize: "1.03em"}}>{tripDays} {LABELS[language].days}</span>
        )}
      </span>
    </div>
      
    <div className="summary-row"><span className="dest-icon" style={{color:'#ff7f8e'}}>📍</span>
      {cities.map((c, idx) => idx > 0 ? <> <span style={{color:"#686fef",fontSize:"1.27em",paddingLeft:3,paddingRight:3}}> {transportIcon(c.transport) || "➔"}</span> {c.city}</> : c.city )}
    </div>

    <div className="summary-row"><span className="dest-icon" style={{fontSize:"1.1em"}}>🍽️</span>
      {cities.map((c, idx) => (idx > 0 ? " ➔ " : "") + foodOptions.filter(f => c.foodChecks && c.foodChecks[f]).join(", ") )}
    </div>

    <div className="summary-row"><span className="dest-icon" style={{color:'#dcdbff'}}>🏨</span>
      {cities.map((c, idx) => (idx > 0 ? " ➔ " : "") + (c.stars ? c.stars + "★ " : "") + (c.accomType || "") )}
    </div>

    <div className="summary-row"><span className="dest-icon" style={{color:"#70eb87"}}>🧾</span>
      {cities.map((c, idx) => (idx > 0 ? " ➔ " : "") + (c.spend || "") )}
    </div>

    <div className="summary-row"><span className="dest-icon" style={{color:'#f077aa'}}>🎟️</span>
      {cities.map((c, idx) => (idx > 0 ? " ➔ " : "") + (c.attractions || ""))}
    </div>

    <div className="summary-row">
      <span className="dest-icon" style={{color: '#70e8eb'}}>🛫</span>
      {cities.filter((c, idx) => idx>0).map((c, idx) => (idx > 0 ? " ➔ " : "") + (transportIcon(c.transport) || "") )}
    </div>
  </div>

  <div className="budget-box">
  <div>{LABELS[language].budgetBox}</div>
  <div style={{fontSize:"1.45em",fontWeight:"bold"}}>
    {formatCurrency(tripTotal, currency)}
  </div>
  <div className="perday">
    {tripDays > 0 ? `${formatCurrency(tripTotal/tripDays, currency)} ${LABELS[language].perDay}` : "--"}
  </div>
  <div className="budget-icon">{currency === 'BRL' ? 'R$' : '€'}</div>
</div>


  <div className="breakdown-section">
  <div style={{fontWeight:700,marginBottom:7}}>{LABELS[language].breakdown}</div>
  {breakdown.map(cat =>
    <div className="bar-row" key={cat.key}>
      <span className="bar-label">
        <span className="ic">{cat.icon}</span>
        {LABELS[language][cat.key]}
      </span>
      <div className="bar">
        <div className={"bar-fill "+cat.className} 
             style={{width: breakdownTotal ? (cat.value/breakdownTotal*100).toFixed(2)+'%' : '0%', minWidth:6}}>
        </div>
      </div>
      <span className="bar-value">{formatCurrency(cat.value, currency)}</span>
      <span className="percent">
        {breakdownTotal ? (cat.value/breakdownTotal*100).toFixed(1)+"%" : "--"}
      </span>
    </div>
  )}
</div>


  <div style={{marginTop: 20, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap'}}>
    <button 
      className="btn"
      onClick={() => {
        const html = generateReport(cities, cityTotals, tripTotal, tripDays, startDate, endDate, totalsCat);
        const element = document.createElement('a');
        const file = new Blob([html], {type: 'text/html'});
        element.href = URL.createObjectURL(file);
        element.download = `trip-report-${new Date().toISOString().split('T')[0]}.html`;
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
      }}
      style={{
        marginTop: 0,
        padding: '14px 24px',
        fontSize: '15px',
        borderRadius: '16px',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        border: 'none',
        boxShadow: '0 4px 15px rgba(102, 126, 234, 0.4)',
        transition: 'all 0.3s ease',
        fontWeight: 'bold'
      }}
      onMouseEnter={(e) => {
        e.target.style.transform = 'translateY(-2px)';
        e.target.style.boxShadow = '0 6px 20px rgba(102, 126, 234, 0.6)';
      }}
      onMouseLeave={(e) => {
        e.target.style.transform = 'translateY(0)';
        e.target.style.boxShadow = '0 4px 15px rgba(102, 126, 234, 0.4)';
      }}
    >
      📥 {LABELS[language].downloadHTML}
    </button>
    
    <button 
      className="btn"
      onClick={() => setShowProposalForm(true)}
      style={{
        marginTop: 0,
        padding: '14px 24px',
        fontSize: '15px',
        borderRadius: '16px',
        background: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
        border: 'none',
        boxShadow: '0 4px 15px rgba(67, 233, 123, 0.4)',
        transition: 'all 0.3s ease',
        fontWeight: 'bold'
      }}
      onMouseEnter={(e) => {
        e.target.style.transform = 'translateY(-2px)';
        e.target.style.boxShadow = '0 6px 20px rgba(67, 233, 123, 0.6)';
      }}
      onMouseLeave={(e) => {
        e.target.style.transform = 'translateY(0)';
        e.target.style.boxShadow = '0 4px 15px rgba(67, 233, 123, 0.4)';
      }}
    >
      📋 {LABELS[language].requestProposal}
    </button>

    <button 
      className="btn"
      onClick={() => {
        const reportHTML = generateReport(cities, cityTotals, tripTotal, tripDays, startDate, endDate, totalsCat);
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.style.visibility = 'hidden';
        iframe.style.height = '0';
        iframe.style.width = '0';
        document.body.appendChild(iframe);
        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        iframeDoc.open();
        iframeDoc.write(reportHTML);
        iframeDoc.close();
        iframeDoc.title = `trip-report-${new Date().toISOString().split('T')[0]}`;
        setTimeout(() => {
          iframe.contentWindow.print();
          setTimeout(() => {
            document.body.removeChild(iframe);
          }, 1000);
        }, 500);
      }}
      style={{
        marginTop: 0,
        padding: '14px 24px',
        fontSize: '15px',
        borderRadius: '16px',
        background: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
        border: 'none',
        boxShadow: '0 4px 15px rgba(245, 87, 108, 0.4)',
        transition: 'all 0.3s ease',
        fontWeight: 'bold'
      }}
      onMouseEnter={(e) => {
        e.target.style.transform = 'translateY(-2px)';
        e.target.style.boxShadow = '0 6px 20px rgba(245, 87, 108, 0.6)';
      }}
      onMouseLeave={(e) => {
        e.target.style.transform = 'translateY(0)';
        e.target.style.boxShadow = '0 4px 15px rgba(245, 87, 108, 0.4)';
      }}
    >
      📥 {LABELS[language].downloadPDF}
    </button>
      
      <div className="share-row">
  <span className="share-label">Share it:</span>

  <div className="share-buttons">
    <button 
      type="button"
      className="share-chip share-email"
      onClick={() => {
        const subject = `Trip Budget Report - €${tripTotal.toFixed(2)}`;
        const body =
          `Check out my trip budget plan!%0A%0A` +
          `📅 ${startDate ? new Date(startDate).toLocaleDateString() : '--'} to ${endDate ? new Date(endDate).toLocaleDateString() : '--'}%0A` +
          `🌍 Cities: ${cities.map(c => c.city).join(' → ')}%0A` +
          `💰 Total Budget: €${tripTotal.toFixed(2)}%0A` +
          `📊 Per Day: €${(tripTotal/tripDays).toFixed(2)}%0A%0A` +
          `View full report at: ${window.location.href}`;
        window.location.href = `mailto:?subject=${subject}&body=${body}`;
      }}
    >
      <span className="share-icon">📧</span>
      <span className="share-text">Email</span>
    </button>

    <button 
      type="button"
      className="share-chip share-whatsapp"
      onClick={() => {
        const text =
          `🌍 My Trip Budget Plan%0A%0A` +
          `📅 ${startDate ? new Date(startDate).toLocaleDateString() : '--'} to ${endDate ? new Date(endDate).toLocaleDateString() : '--'}%0A` +
          `🏙️ ${cities.map(c => c.city).join(' → ')}%0A` +
          `💰 Total: €${tripTotal.toFixed(2)} (€${(tripTotal/tripDays).toFixed(2)}/day)%0A%0A` +
          `🏨 Accommodation: €${totalsCat.accommodation.toFixed(2)}%0A` +
          `✈️ Transport: €${totalsCat.transport.toFixed(2)}%0A` +
          `🍽️ Food: €${totalsCat.food.toFixed(2)}%0A` +
          `🎁 Extras: €${totalsCat.extras.toFixed(2)}`;
        window.open(`https://wa.me/?text=${text}`, '_blank');
      }}
    >
      <span className="share-icon">🟢</span>
      <span className="share-text">WhatsApp</span>
    </button>

    <button 
      type="button"
      className="share-chip share-twitter"
      onClick={() => {
        const text = `My Trip Budget: €${tripTotal.toFixed(2)} for ${tripDays} days visiting ${cities.map(c => c.city).join(', ')}`;
        const url = window.location.href;
        window.open(
          `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`,
          '_blank'
        );
      }}
    >
      <span className="share-icon">🐦</span>
      <span className="share-text">Twitter</span>
    </button>

    <button 
      type="button"
      className="share-chip share-facebook"
      onClick={() => {
        const text = `Check out my trip budget plan: €${tripTotal.toFixed(2)} for ${tripDays} days!`;
        const url = window.location.href;
        window.open(
          `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}&quote=${encodeURIComponent(text)}`,
          '_blank'
        );
      }}
    >
      <span className="share-icon">📘</span>
      <span className="share-text">Facebook</span>
    </button>
  </div>
  
  
  <div className="buffer-tip">
          <span className="ic">🌟</span>
          Consider adding <span className="b">€{buffer.toFixed(2)}</span> <span className="pct">(15%)</span> as a safety buffer for unexpected expenses.
        </div>

</div>


  </div>
</div>

{showProposalForm && (
  <div
    style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      background: 'rgba(0, 0, 0, 0.8)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      zIndex: 10000,
    }}
  >
    <div
      className="card"
      style={{
        maxWidth: '600px',
        width: '90%',
        maxHeight: '90vh',
        overflow: 'auto',
        position: 'relative',
        padding: '20px',
      }}
    >
      <button
        onClick={() => setShowProposalForm(false)}
        style={{
          position: 'absolute',
          top: '15px',
          right: '15px',
          background: '#ff4757',
          color: 'white',
          border: 'none',
          borderRadius: '50%',
          width: '30px',
          height: '30px',
          cursor: 'pointer',
          fontSize: '18px',
          zIndex: 10,
        }}
      >
        ×
      </button>

      <div className="header">📋 {LABELS[language].requestProposal}</div>

      <form onSubmit={handleProposalSubmit} autoComplete="off" style={{marginTop: '20px', display: 'grid', gap: '15px'}}>
        
        <label style={{display: 'block'}}>
          {LABELS[language].email} *
          <input
            type="email"
            required
            value={proposalData.email}
            onChange={(e) => setProposalData({...proposalData, email: e.target.value})}
            style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
          />
        </label>

        <label style={{display: 'block'}}>
          {LABELS[language].phone} *
          <input
            type="tel"
            required
            value={proposalData.phone}
            onChange={(e) => setProposalData({...proposalData, phone: e.target.value})}
            style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
          />
        </label>

        <label style={{display: 'block'}}>
          {LABELS[language].fullName} *
          <input
            type="text"
            required
            value={proposalData.fullName}
            onChange={(e) => setProposalData({...proposalData, fullName: e.target.value})}
            style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
          />
        </label>

        <label style={{display: 'block'}}>
          {LABELS[language].birthDate} *
          <input
            type="date"
            required
            value={proposalData.birthDate}
            onChange={(e) => setProposalData({...proposalData, birthDate: e.target.value})}
            style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
          />
        </label>

        <div style={{borderTop: '2px solid #0a84ff', paddingTop: '15px', marginTop: '10px'}}>
          <h3 style={{margin: '0 0 15px 0', color: '#0a84ff'}}>Passport Information</h3>
        </div>

        <label style={{display: 'block'}}>
          {LABELS[language].passportNumber} *
          <input
            type="text"
            required
            value={proposalData.passportNumber}
            onChange={(e) => setProposalData({...proposalData, passportNumber: e.target.value})}
            style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
          />
        </label>

       
        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px'}}>
          <label style={{display: 'block'}}>
            {LABELS[language].issueDate} *
            <input
              type="date"
              required
              value={proposalData.issueDate}
              onChange={(e) => setProposalData({...proposalData, issueDate: e.target.value})}
              style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
            />
          </label>

          <label style={{display: 'block'}}>
            {LABELS[language].expiryDate} *
            <input
              type="date"
              required
              value={proposalData.expiryDate}
              onChange={(e) => setProposalData({...proposalData, expiryDate: e.target.value})}
              style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
            />
          </label>
        </div>

        <label style={{display: 'block'}}>
          {LABELS[language].issuingAuthority} *
          <input
            type="text"
            required
            value={proposalData.issuingAuthority}
            onChange={(e) => setProposalData({...proposalData, issuingAuthority: e.target.value})}
            style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
          />
        </label>
        
         <label style={{display: 'block'}}>
          {LABELS[language].personalID} *
          <input
            type="text"
            required
            value={proposalData.personalID}
            onChange={(e) => setProposalData({...proposalData, personalID: e.target.value})}
            style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
          />
        </label>
        
        <label style={{display: 'block'}}>
          {LABELS[language].wiseaccount} *
          <input
            type="text"
            required
            value={proposalData.wiseaccount}
            onChange={(e) => setProposalData({...proposalData, wiseaccount: e.target.value})}
            style={{width: '100%', padding: '10px', borderRadius: '8px', border: '1px solid #ddd', marginTop: '5px'}}
          />
        </label>

        <button
          type="submit"
          style={{
            padding: '14px 24px',
            fontSize: '15px',
            borderRadius: '16px',
            background: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
            border: 'none',
            boxShadow: '0 4px 15px rgba(67, 233, 123, 0.4)',
            cursor: 'pointer',
            fontWeight: 'bold',
            color: 'white',
            marginTop: '10px'
          }}
        >
          {LABELS[language].confirmSend || 'Submit'}
        </button>
      </form>
    </div>
  </div>
)}



{showReviewModal && (
  <div style={{position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.8)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 10000}}>
    <div className="card" style={{maxWidth: '900px', width: '95%', maxHeight: '90vh', overflow: 'auto', position: 'relative'}}>
      <button onClick={() => setShowReviewModal(false)} style={{position: 'absolute', top: '15px', right: '15px', background: '#ff4757', color: 'white', border: 'none', borderRadius: '50%', width: '30px', height: '30px', cursor: 'pointer', fontSize: '18px', zIndex: 10}}>×</button>
      
      <div className="header">{LABELS[language].reviewProposal}</div>
      
      <div style={{padding: '20px'}}>
        <div style={{marginBottom: '20px', borderBottom: '2px solid #0a84ff', paddingBottom: '10px'}}>
          <h3 style={{color: '#0a84ff', margin: '0 0 10px 0'}}>{LABELS[language].fullName} / {LABELS[language].personalID}</h3>
          <div style={{display: 'grid', gap: '8px'}}>
            <div><strong>{LABELS[language].fullName}:</strong> {proposalData.fullName}</div>
            <div><strong>{LABELS[language].email}:</strong> {proposalData.email}</div>
            <div><strong>{LABELS[language].phone}:</strong> {proposalData.phone}</div>
            <div><strong>{LABELS[language].birthDate}:</strong> {proposalData.birthDate ? new Date(proposalData.birthDate).toLocaleDateString() : ''}</div>
          </div>
        </div>
        
        <div style={{marginBottom: '20px', borderBottom: '2px solid #0a84ff', paddingBottom: '10px'}}>
          <h3 style={{color: '#0a84ff', margin: '0 0 10px 0'}}>{LABELS[language].passportNumber}</h3>
          <div style={{display: 'grid', gap: '8px'}}>
            <div><strong>{LABELS[language].passportNumber}:</strong> {proposalData.passportNumber}</div>
            
            <div><strong>{LABELS[language].issueDate}:</strong> {proposalData.issueDate ? new Date(proposalData.issueDate).toLocaleDateString() : ''}</div>
            <div><strong>{LABELS[language].expiryDate}:</strong> {proposalData.expiryDate ? new Date(proposalData.expiryDate).toLocaleDateString() : ''}</div>
            <div><strong>{LABELS[language].issuingAuthority}:</strong> {proposalData.issuingAuthority}</div>
            <div><strong>{LABELS[language].personalID}:</strong> {proposalData.personalID}</div>
          </div>
        </div>
        
        <div style={{marginBottom: '20px', borderBottom: '2px solid #0a84ff', paddingBottom: '10px'}}>
          <h3 style={{color: '#0a84ff', margin: '0 0 10px 0'}}>{LABELS[language].wiseaccount}</h3>
          <div style={{display: 'grid', gap: '8px'}}>
            <div><strong>{LABELS[language].wiseaccount}:</strong> {proposalData.wiseaccount}</div>
            <div><strong>{LABELS[language].personalID}:</strong> {proposalData.personalID}</div>
            
          </div>
        </div>
        
        <div style={{marginBottom: '20px', borderBottom: '2px solid #0a84ff', paddingBottom: '10px'}}>
          <h3 style={{color: '#0a84ff', margin: '0 0 10px 0'}}>{LABELS[language].tripOverview}</h3>
          <div style={{display: 'grid', gap: '8px'}}>
            <div><strong>{LABELS[language].tripOverview} {LABELS[language].days}:</strong> {startDate ? new Date(startDate).toLocaleDateString() : '--'} {LABELS[language].to} {endDate ? new Date(endDate).toLocaleDateString() : '--'}</div>
            <div><strong>{LABELS[language].tripDuration}:</strong> {tripDays} {LABELS[language].days}</div>
            <div><strong>{LABELS[language].citiesVisited}:</strong> {cities.map(c => c.city).join(' → ')}</div>
            <div><strong>{LABELS[language].totalBudget}:</strong> €{tripTotal.toFixed(2)}</div>
            <div><strong>{LABELS[language].perDayAverage}:</strong> €{(tripTotal/tripDays).toFixed(2)}</div>
          </div>
        </div>

        <div style={{marginBottom: '20px', borderBottom: '2px solid #0a84ff', paddingBottom: '10px'}}>
          <h3 style={{color: '#0a84ff', margin: '0 0 10px 0'}}>{LABELS[language].breakdown}</h3>
          <div style={{display: 'grid', gap: '8px'}}>
            <div><strong>🏨 {LABELS[language].accommodation}:</strong> €{totalsCat.accommodation.toFixed(2)}</div>
            <div><strong>💰 {LABELS[language].transportation}:</strong> €{totalsCat.transport.toFixed(2)}</div>
            <div><strong>🍽️ {LABELS[language].food}:</strong> €{totalsCat.food.toFixed(2)}</div>
            <div><strong>🎁 {LABELS[language].extras}:</strong> €{totalsCat.extras.toFixed(2)}</div>
          </div>
        </div>

        <div style={{marginBottom: '20px', borderBottom: '2px solid #0a84ff', paddingBottom: '10px'}}>
          <h3 style={{color: '#0a84ff', margin: '0 0 10px 0'}}>{LABELS[language].detailsPerCity}</h3>
          <table style={{width: '100%', borderCollapse: 'collapse', fontSize: '13px'}}>
            <thead>
              <tr style={{background: '#0a84ff', color: 'white'}}>
                <th style={{padding: '8px', textAlign: 'left'}}>{LABELS[language].city}</th>
                <th style={{padding: '8px', textAlign: 'left'}}>{LABELS[language].days}</th>
                <th style={{padding: '8px', textAlign: 'left'}}>{LABELS[language].dailyCost}</th>
                <th style={{padding: '8px', textAlign: 'left'}}>{LABELS[language].totalBudget}</th>
              </tr>
            </thead>
            <tbody>
              {cities.map((city, idx) => {
                const days = city.startDate && city.endDate ? Math.max(1, Math.round((new Date(city.endDate) - new Date(city.startDate))/(1000*60*60*24))) : 1;
                const total = cityTotals[idx] || 0;
                const daily = days ? (total/days).toFixed(2) : total.toFixed(2);
                return (
                  <tr key={idx} style={{borderBottom: '1px solid #ddd'}}>
                    <td style={{padding: '8px'}}>{city.city}</td>
                    <td style={{padding: '8px'}}>{days}</td>
                    <td style={{padding: '8px'}}>€{daily}</td>
                    <td style={{padding: '8px'}}><strong>€{total.toFixed(2)}</strong></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div style={{marginBottom: '20px'}}>
          <h3 style={{color: '#ffffff', margin: '0 0 10px 0'}}>{LABELS[language].detailsPerCity}</h3>
          {cities.map((city, idx) => (
            <div key={idx} style={{
              marginBottom: '15px',
              padding: '10px',
              background: '#ffffff',
              borderRadius: '8px',
              border: '1px solid #ddd',
              color: '#ffffff'
            }}>
              <h4 style={{margin: '0 0 8px 0', color: '#ffffff'}}>{city.city}</h4>
              <div style={{display: 'grid', gap: '5px', fontSize: '13px', color: '#000000'}}>
                <div><strong style={{color: '#000000'}}>{LABELS[language].tripOverview} {LABELS[language].days}:</strong> {city.startDate} to {city.endDate}</div>
                <div><strong style={{color: '#000000'}}>{LABELS[language].accommodation}:</strong> {city.stars}★ {city.accomType}</div>
                {idx > 0 && <div><strong style={{color: '#000000'}}>{LABELS[language].transportation}:</strong> {city.transport} ({city.transportPrice})</div>}
                <div><strong style={{color: '#000000'}}>{LABELS[language].mealsOptions}</strong> {foodOptions.filter(f => city.foodChecks && city.foodChecks[f]).join(', ') || 'None selected'}</div>
                <div><strong style={{color: '#000000'}}>{LABELS[language].spendAmount}:</strong> {city.spend}</div>
                <div><strong style={{color: '#000000'}}>{LABELS[language].attractions}:</strong> {city.attractions}</div>
              </div>
            </div>
          ))}
             
        </div>

     
        
        
        
        <div style={{background: '#5a4fcf', padding: '20px', borderRadius: '8px', textAlign: 'center', marginTop: '30px'}}>
          <p style={{marginBottom: '15px', fontSize: '14px'}}>{LABELS[language].reviewProposal} <strong>contact@tunvolo.com</strong></p>
          <button onClick={confirmAndSendEmail} style={{padding: '14px 30px', fontSize: '15px', background: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer', fontWeight: 'bold', marginRight: '10px'}}>
            ✓ {LABELS[language].confirmSend}
          </button>
          <button onClick={() => setShowReviewModal(false)} style={{padding: '14px 30px', fontSize: '15px', background: '#ff4757', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer', fontWeight: 'bold'}}>
            ✗ {LABELS[language].cancel}
          </button>
        </div>
      </div>
    </div>
  </div>
)}



    </>
  );
}

// ... ReactDOM line
ReactDOM.createRoot(document.getElementById("app-root")).render(<TripPlannerApp />);
