// Home page — API'den veri çeker, fallback static data kullanır

// ────────────────────────────────────────────────────────
// Araç görseli yönetimi
// Yerel dosya: /img/vehicles/{key}.jpg  (öncelikli)
// Fallback: /img/vehicles/{key}.webp → sonra CDN
// Dosyalar buraya konulmalı:
//   wwwroot/img/vehicles/shuttle.jpg  (Mercedes Sprinter 3/4 ön)
//   wwwroot/img/vehicles/taxi.jpg     (Toyota Corolla / Renault Talisman 3/4 ön)
//   wwwroot/img/vehicles/vip.jpg      (Mercedes E-Class W213 3/4 ön)
//   wwwroot/img/vehicles/minivan.jpg  (Mercedes Vito / V-Class 3/4 ön)
// ────────────────────────────────────────────────────────

// VehicleType enum → görsel anahtar
const vtToKey = (vt, name) => {
  if (vt === 0) return "shuttle";
  if (vt === 1) return "taxi";
  if (vt === 2) return "vip";
  if (vt === 3) return "minivan";
  // isim bazlı fallback
  const n = (name || "").toLowerCase();
  if (n.includes("shuttle") || n.includes("sprinter")) return "shuttle";
  if (n.includes("vip"))    return "vip";
  if (n.includes("minivan") || n.includes("vito") || n.includes("v-class")) return "minivan";
  return "taxi";
};

// Placeholder SVG car silhouetteleri — gerçek resim yoksa gösterilir
const CAR_SVG = {
  shuttle: (
    <svg viewBox="0 0 320 180" fill="none" xmlns="http://www.w3.org/2000/svg" style={{width:"85%",height:"85%",opacity:.18}}>
      <rect x="20" y="60" width="280" height="90" rx="12" fill="currentColor"/>
      <rect x="30" y="40" width="200" height="50" rx="8" fill="currentColor"/>
      <circle cx="70"  cy="158" r="20" fill="currentColor"/>
      <circle cx="250" cy="158" r="20" fill="currentColor"/>
      <rect x="40" y="55" width="55" height="35" rx="4" fill="white" opacity=".3"/>
      <rect x="105" y="55" width="55" height="35" rx="4" fill="white" opacity=".3"/>
      <rect x="170" y="55" width="55" height="35" rx="4" fill="white" opacity=".3"/>
    </svg>
  ),
  taxi: (
    <svg viewBox="0 0 320 180" fill="none" xmlns="http://www.w3.org/2000/svg" style={{width:"85%",height:"85%",opacity:.18}}>
      <rect x="20" y="80" width="280" height="70" rx="10" fill="currentColor"/>
      <path d="M60 80 L80 40 L240 40 L270 80Z" fill="currentColor"/>
      <circle cx="75"  cy="158" r="20" fill="currentColor"/>
      <circle cx="245" cy="158" r="20" fill="currentColor"/>
      <rect x="90" y="48" width="60" height="30" rx="4" fill="white" opacity=".3"/>
      <rect x="165" y="48" width="60" height="30" rx="4" fill="white" opacity=".3"/>
    </svg>
  ),
  vip: (
    <svg viewBox="0 0 320 180" fill="none" xmlns="http://www.w3.org/2000/svg" style={{width:"85%",height:"85%",opacity:.18}}>
      <rect x="15" y="85" width="290" height="65" rx="10" fill="currentColor"/>
      <path d="M55 85 L80 45 L240 45 L275 85Z" fill="currentColor"/>
      <circle cx="72"  cy="158" r="20" fill="currentColor"/>
      <circle cx="248" cy="158" r="20" fill="currentColor"/>
      <rect x="88" y="52" width="65" height="30" rx="4" fill="white" opacity=".3"/>
      <rect x="167" y="52" width="65" height="30" rx="4" fill="white" opacity=".3"/>
      <rect x="20" y="90" width="80" height="25" rx="3" fill="white" opacity=".15"/>
    </svg>
  ),
  minivan: (
    <svg viewBox="0 0 320 180" fill="none" xmlns="http://www.w3.org/2000/svg" style={{width:"85%",height:"85%",opacity:.18}}>
      <rect x="20" y="65" width="280" height="85" rx="10" fill="currentColor"/>
      <path d="M30 65 L50 35 L260 35 L280 65Z" fill="currentColor"/>
      <circle cx="72"  cy="158" r="20" fill="currentColor"/>
      <circle cx="248" cy="158" r="20" fill="currentColor"/>
      <rect x="38" y="43" width="50" height="30" rx="4" fill="white" opacity=".3"/>
      <rect x="100" y="43" width="50" height="30" rx="4" fill="white" opacity=".3"/>
      <rect x="165" y="43" width="50" height="30" rx="4" fill="white" opacity=".3"/>
    </svg>
  ),
};

// Araç görsel komponenti — yerel → CDN → SVG fallback
const VehicleImg = ({ vt, name, tag, accent = "var(--blue)" }) => {
  const key = vtToKey(vt, name);
  // Önce yerel dosya dene, sonra SVG göster
  const [src, setSrc] = React.useState(`img/vehicles/${key}.jpg`);
  const [failed, setFailed] = React.useState(false);

  const handleError = () => {
    if (src.endsWith(".jpg"))      { setSrc(`img/vehicles/${key}.webp`); return; }
    if (src.endsWith(".webp"))     { setSrc(`img/vehicles/${key}.png`);  return; }
    setFailed(true);
  };

  return (
    <div style={{ width: "100%", height: "100%", position: "relative", minHeight: 180,
                  background: "linear-gradient(135deg,#F0F4FF 0%,#E8F0FC 100%)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  overflow: "hidden" }}>
      {tag && <div className="vehicle-img-tag">{tag}</div>}
      {failed ? (
        /* SVG silhouette */
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center",
                      width: "100%", height: "100%", color: accent, flexDirection: "column", gap: 8 }}>
          {CAR_SVG[key]}
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--gray-400)",
                         letterSpacing: ".1em", textTransform: "uppercase" }}>
            {name}
          </span>
        </div>
      ) : (
        <img src={src} alt={name} onError={handleError}
             style={{ width: "100%", height: "100%", objectFit: "contain",
                      objectPosition: "center bottom", display: "block",
                      padding: "12px 8px 0" }}/>
      )}
    </div>
  );
};

// Statik fallback verisi
const VEHICLES_FALLBACK = [
  { id: "shuttle", vehicleType: 0, name: "Paylaşımlı Shuttle", model: "Mercedes Sprinter / VW Crafter", maxPassengers: 16, maxBaggage: 16, priceInTRY: 280, isFeatured: false, features: ["A/C Klimalı","Wi-Fi","Paylaşımlı"] },
  { id: "taxi",    vehicleType: 1, name: "Özel Taksi Transfer", model: "Toyota Corolla / Renault Talisman", maxPassengers: 3, maxBaggage: 3, priceInTRY: 1200, isFeatured: false, features: ["A/C Klimalı","Özel Transfer","Wi-Fi"] },
  { id: "vip",     vehicleType: 2, name: "VIP Premium Transfer", model: "Mercedes E-Class W213", maxPassengers: 3, maxBaggage: 3, priceInTRY: 2400, isFeatured: true,  features: ["Premium Deri","Wi-Fi","Su & Atıştırmalık","Karşılama"] },
  { id: "minivan", vehicleType: 3, name: "Aile / Grup Minivan",  model: "Mercedes Vito Tourer", maxPassengers: 7, maxBaggage: 7, priceInTRY: 1800, isFeatured: false, features: ["A/C Klimalı","Wi-Fi","Geniş Bagaj"] },
];

const ROUTES_FALLBACK = [
  { fromLocationName: "AYT Havalimanı", toLocationName: "Lara Otelleri", durationMinutes: 20, distanceKm: 12, basePriceInTRY: 950 },
  { fromLocationName: "AYT Havalimanı", toLocationName: "Belek", durationMinutes: 35, distanceKm: 35, basePriceInTRY: 1450 },
  { fromLocationName: "AYT Havalimanı", toLocationName: "Kemer", durationMinutes: 55, distanceKm: 55, basePriceInTRY: 1850 },
  { fromLocationName: "AYT Havalimanı", toLocationName: "Side / Manavgat", durationMinutes: 65, distanceKm: 65, basePriceInTRY: 2150 },
  { fromLocationName: "AYT Havalimanı", toLocationName: "Alanya", durationMinutes: 105, distanceKm: 125, basePriceInTRY: 3200 },
  { fromLocationName: "AYT Havalimanı", toLocationName: "Kalkan / Kaş", durationMinutes: 165, distanceKm: 200, basePriceInTRY: 5800 },
];

const REVIEWS_FALLBACK = [
  { authorName: "Marcus W.", country: "🇩🇪 Berlin", text: "Excellent service from start to finish. Driver was waiting at the airport with a sign, the Mercedes was spotless, and the price was exactly as quoted.", stars: 5, createdAt: "2026-03-15" },
  { authorName: "Elena K.", country: "🇷🇺 Moscow", text: "Очень удобный и быстрый трансфер до отеля в Белеке. Водитель встретил нас сразу после паспортного контроля. Машина просторная и чистая.", stars: 5, createdAt: "2026-02-10" },
  { authorName: "Ayşe T.", country: "🇹🇷 İstanbul", text: "Tatilimizin başında stresli bir zaman yaşamadık. Şoför çok kibardı, araç temiz ve klimalıydı. Fiyat değişmedi, web siteden gördüğüm rakam neyse onu ödedik.", stars: 5, createdAt: "2026-01-20" },
];

// API'den veri çeken hook — hata olursa fallback
function useApiData(path, fallback) {
  const [data, setData] = React.useState(fallback);
  React.useEffect(() => {
    engApi.get(path)
      .then(d => setData(d))
      .catch(() => {});
  }, []);
  return data;
}

function fmtDuration(mins) {
  if (!mins) return "—";
  const h = Math.floor(mins / 60), m = mins % 60;
  return h > 0 ? `${h}s ${m > 0 ? m + "dk" : ""}`.trim() : `${m} dk`;
}

const HomePage = ({ lang, ccy, query, setQuery, onSearch, heroVariant, onNav }) => {
  const t = TRANSLATIONS[lang];
  const vehicles = useApiData("/api/vehicle", VEHICLES_FALLBACK);
  const routes   = useApiData("/api/route",   ROUTES_FALLBACK);
  const reviews  = useApiData("/api/review",  REVIEWS_FALLBACK);

  // Hero section'ı overflow:hidden'dan çıkarmak için search widget ayrı render edilir
  const SearchBar = () => (
    <div style={{ maxWidth: 1320, margin: "0 auto", padding: "0 32px", position: "relative", zIndex: 100 }}>
      <SearchWidget lang={lang} ccy={ccy} query={query} setQuery={setQuery} onSearch={onSearch}/>
    </div>
  );

  const HeroSplit = () => (
    <>
      <section className="hero hero-split" style={{ paddingBottom: 0 }}>
        <div className="hero-split-grid">
          <div>
            <div className="hero-eyebrow"><span className="dot"></span>{t.hero.eyebrow}</div>
            <h1 className="hero-title">
              {t.hero.title} <em>{t.hero.titleEm}</em><br/>
              <span className="underline">{t.hero.titleRest}</span>
            </h1>
            <p className="hero-sub">{t.hero.sub}</p>
            <div className="hero-trust">
              <div className="hero-trust-item"><Icon name="check" size={18} style={{ color: "var(--red-bright)" }}/> {t.hero.trustFree}</div>
              <div className="hero-trust-item"><Icon name="clock" size={18} style={{ color: "var(--red-bright)" }}/> {t.hero.trustWait}</div>
              <div className="hero-trust-item"><Icon name="plane" size={18} style={{ color: "var(--red-bright)" }}/> {t.hero.trustFlight}</div>
            </div>
          </div>
          <div className="hero-visual">
            <div className="hero-visual-card">
              <img src="https://images.unsplash.com/photo-1555215695-3004980ad54e?w=800&q=80"
                   alt="VIP Transfer" style={{ width:"100%", height:"100%", objectFit:"cover", borderRadius:"inherit" }}
                   onError={e => { e.target.style.display="none"; }}/>
            </div>
            <div className="hero-floating-card tl">
              <div className="icon-bubble"><Icon name="star" size={20}/></div>
              <div>
                <div className="num">4.9<span style={{ fontSize: 14, opacity: .6 }}>/5</span></div>
                <div className="label">2,847 Yorum</div>
              </div>
            </div>
            <div className="hero-floating-card br">
              <div className="icon-bubble" style={{ background: "var(--blue)" }}><Icon name="users" size={20}/></div>
              <div>
                <div className="num">200K+</div>
                <div className="label">Mutlu Yolcu</div>
              </div>
            </div>
          </div>
        </div>
        <div style={{ height: 64 }}></div>
      </section>
      {/* Search widget HERO DIŞINDA — overflow:hidden sorununu çözer */}
      <div style={{ background: "var(--navy-900)", paddingBottom: 48 }}>
        <SearchBar/>
      </div>
    </>
  );

  const HeroFull = () => (
    <>
      <section className="hero hero-full" style={{ paddingBottom: 0 }}>
        <div className="hero-full-content">
          <div className="hero-eyebrow" style={{ margin: "0 auto 22px" }}><span className="dot"></span>{t.hero.eyebrow}</div>
          <h1 className="hero-title">{t.hero.title}<br/><em>{t.hero.titleEm}</em> {t.hero.titleRest}</h1>
          <p className="hero-sub" style={{ margin: "0 auto 40px" }}>{t.hero.sub}</p>
        </div>
        <div style={{ height: 40 }}></div>
      </section>
      <div style={{ background: "var(--navy-950)", paddingBottom: 48 }}>
        <SearchBar/>
      </div>
    </>
  );

  const HeroPhoto = () => (
    <>
      <section className="hero hero-photo" style={{ paddingBottom: 0 }}>
        <div className="hero-photo-bg"></div>
        <div className="hero-photo-content">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 48, alignItems: "center" }}>
            <div>
              <div className="hero-eyebrow"><span className="dot"></span>{t.hero.eyebrow}</div>
              <h1 className="hero-title" style={{ fontSize: 72 }}>
                {t.hero.title} <em>{t.hero.titleEm}</em>{" "}{t.hero.titleRest}
              </h1>
              <p className="hero-sub">{t.hero.sub}</p>
              <div className="hero-trust">
                <div className="hero-trust-item"><Icon name="check" size={18} style={{ color: "var(--red-bright)" }}/> {t.hero.trustFree}</div>
                <div className="hero-trust-item"><Icon name="clock" size={18} style={{ color: "var(--red-bright)" }}/> {t.hero.trustWait}</div>
                <div className="hero-trust-item"><Icon name="plane" size={18} style={{ color: "var(--red-bright)" }}/> {t.hero.trustFlight}</div>
              </div>
            </div>
          </div>
        </div>
        <div style={{ height: 48 }}></div>
      </section>
      <div style={{ background: "var(--navy-950)", paddingBottom: 48 }}>
        <SearchBar/>
      </div>
    </>
  );

  const Hero = heroVariant === "full" ? HeroFull : heroVariant === "photo" ? HeroPhoto : HeroSplit;

  return (
    <div>
      <Hero/>

      {/* Araçlar */}
      <section className="section section-light">
        <div className="container">
          <div className="section-head-row">
            <div>
              <div className="section-eyebrow">{t.vehicles.eyebrow}</div>
              <h2 className="section-title">{t.vehicles.title}</h2>
              <p className="section-sub">{t.vehicles.sub}</p>
            </div>
            <button className="btn btn-ghost" onClick={onSearch}>Tüm Filo <Icon name="arrowRight" size={16}/></button>
          </div>
          <div className="vehicle-grid">
            {vehicles.slice(0, 4).map((v, i) => {
              const p = fmtPrice(v.priceInTRY || v.priceTry, ccy);
              const catLabels = ["SHUTTLE","TAXİ","VIP CAR","MİNİVAN"];
              const catLabel = catLabels[v.vehicleType] || "ARAÇ";
              return (
                <div key={v.id || i} className={"vehicle-card" + (v.isFeatured || v.featured ? " featured" : "")} onClick={onSearch}>
                  <div className="vehicle-img" style={{ padding: 0, overflow: "hidden" }}>
                    <VehicleImg vt={v.vehicleType} name={v.name} tag={catLabel}/>
                  </div>
                  <div className="vehicle-body">
                    <h3 className="vehicle-name">{v.name}</h3>
                    <p className="vehicle-model">{v.model}</p>
                    <div className="vehicle-specs">
                      <div className="vehicle-spec"><Icon name="users" size={15} className="icon"/> {v.maxPassengers || v.pax}</div>
                      <div className="vehicle-spec"><Icon name="luggage" size={15} className="icon"/> {v.maxBaggage || v.bag}</div>
                      <div className="vehicle-spec"><Icon name="snow" size={15} className="icon"/> A/C</div>
                    </div>
                    <div className="vehicle-price-row">
                      <div>
                        <div className="vehicle-price-label">{t.vehicles.from}</div>
                        <div className="vehicle-price"><span className="currency">{p.symbol}</span>{p.value}</div>
                      </div>
                      <button className="btn btn-secondary" style={{ padding: "8px 14px", fontSize: 13 }} onClick={onSearch}>{t.vehicles.view}</button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* İstatistikler */}
      <section className="section section-dark" style={{ padding: "80px 32px" }}>
        <div className="container">
          <div className="stats">
            <div className="stat"><div className="stat-num">200K<em>+</em></div><div className="stat-label">Tamamlanan transfer</div></div>
            <div className="stat"><div className="stat-num">4.9<em>★</em></div><div className="stat-label">Müşteri puanı (2,847 yorum)</div></div>
            <div className="stat"><div className="stat-num">12<em>yıl</em></div><div className="stat-label">Sektör tecrübesi</div></div>
            <div className="stat"><div className="stat-num">24<em>/7</em></div><div className="stat-label">Operasyon ve destek</div></div>
          </div>
        </div>
      </section>

      {/* Popüler Güzergahlar */}
      <section className="section section-gray">
        <div className="container">
          <div className="section-head">
            <div className="section-eyebrow">{t.routes.eyebrow}</div>
            <h2 className="section-title">{t.routes.title}</h2>
          </div>
          <div className="route-grid">
            {routes.slice(0, 6).map((r, i) => {
              const p = fmtPrice(r.basePriceInTRY || r.priceTry, ccy);
              const dur = r.durationMinutes ? fmtDuration(r.durationMinutes) : r.duration;
              const dist = r.distanceKm ? `${r.distanceKm} km` : r.distance;
              const from = r.fromLocationName || r.from;
              const to = r.toLocationName || r.to;
              return (
                <div key={i} className="route-card" onClick={onSearch} style={{ cursor: "pointer" }}>
                  <div className="route-pair">
                    <span style={{ flex: 1 }}>{from}</span>
                    <Icon name="arrowRight" size={18} className="arrow"/>
                    <span style={{ flex: 1, textAlign: "right" }}>{to}</span>
                  </div>
                  <div className="route-meta">
                    <span><Icon name="clock" size={13}/> {dur}</span>
                    <span><Icon name="map" size={13}/> {dist}</span>
                  </div>
                  <div className="route-price-row">
                    <span className="route-from">{t.vehicles.from}</span>
                    <span className="route-amount"><span style={{ fontSize: 18, color: "var(--gray-500)" }}>{p.symbol}</span>{p.value}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* Neden ENG Transfer */}
      <section className="section section-light">
        <div className="container">
          <div className="section-head">
            <div className="section-eyebrow">{t.features.eyebrow}</div>
            <h2 className="section-title">{t.features.title}</h2>
          </div>
          <div className="feature-grid">
            <div className="feature">
              <div className="feature-icon red"><Icon name="tag" size={22}/></div>
              <h3 className="feature-title">{t.features.f1t}</h3>
              <p className="feature-desc">{t.features.f1d}</p>
            </div>
            <div className="feature">
              <div className="feature-icon"><Icon name="plane" size={22}/></div>
              <h3 className="feature-title">{t.features.f2t}</h3>
              <p className="feature-desc">{t.features.f2d}</p>
            </div>
            <div className="feature">
              <div className="feature-icon"><Icon name="user" size={22}/></div>
              <h3 className="feature-title">{t.features.f3t}</h3>
              <p className="feature-desc">{t.features.f3d}</p>
            </div>
            <div className="feature">
              <div className="feature-icon red"><Icon name="sign" size={22}/></div>
              <h3 className="feature-title">{t.features.f4t}</h3>
              <p className="feature-desc">{t.features.f4d}</p>
            </div>
          </div>
        </div>
      </section>

      {/* Müşteri Yorumları */}
      <section className="section section-gray">
        <div className="container">
          <div className="section-head">
            <div className="section-eyebrow">{t.reviews.eyebrow}</div>
            <h2 className="section-title">{t.reviews.title}</h2>
          </div>
          <div className="review-grid">
            {reviews.slice(0, 3).map((r, i) => {
              const name = r.authorName || r.name;
              const country = r.country;
              const text = r.text;
              const stars = r.stars;
              return (
                <div key={i} className="review-card">
                  <div className="review-stars">
                    {[...Array(stars)].map((_, j) => <Icon key={j} name="star" size={16}/>)}
                  </div>
                  <p className="review-text">"{text}"</p>
                  <div className="review-author">
                    <div className="review-avatar">{name?.charAt(0)}</div>
                    <div style={{ flex: 1 }}>
                      <div className="review-name">{name}</div>
                      <div className="review-meta">{country}</div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section style={{ padding: "0 32px 96px", background: "var(--gray-50)" }}>
        <div className="container">
          <div className="cta-banner">
            <div>
              <h2>{t.cta.title}</h2>
              <p>{t.cta.sub}</p>
            </div>
            <div className="cta-banner-actions">
              <button className="btn btn-primary btn-lg" onClick={onSearch}>{t.cta.btn}<Icon name="arrowRight" size={16}/></button>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

window.HomePage = HomePage;
window.VEHICLES = VEHICLES_FALLBACK;
window.VehicleImg = VehicleImg;
window.fmtDuration = fmtDuration;
