/* global React */
/* ============================================================
   FRONT LINE — Bilingual Router + Meta Manager
   - Path-based routing: /en/about, /el/etaireia, etc.
   - Language toggle preserves the current page (swaps slugs).
   - Updates <html lang>, <title>, meta description, OG, Twitter,
     canonical, and hreflang alternates on every nav.
   - Works on http(s); falls back to hash routing on file://
   ============================================================ */

const { useState: useStateR, useEffect: useEffectR, useCallback: useCallbackR } = React;

const SITE_ORIGIN = 'https://frontline-ltd.com';

/* --------- Slug map per language --------- */
/* page key → { en, el } slug. Empty slug = the language root. */
const SLUGS = {
  home:     { en: '',           el: '' },
  about:    { en: 'about',      el: 'etairia' },
  services: { en: 'services',   el: 'ypiresies' },
  network:  { en: 'network',    el: 'diktyo' },
  newsroom: { en: 'newsroom',   el: 'nea' },
  contact:  { en: 'contact',    el: 'epikoinonia' },
};

const PAGE_KEYS = Object.keys(SLUGS);

/* --------- Per-page meta (title, description, primary keyword) --------- */
const META = {
  home: {
    en: {
      title: 'Freight Forwarder in Piraeus, Greece | Frontline',
      description: 'Piraeus-based freight forwarder and ship agency: sea, air and road forwarding, customs clearance, ship supply and on-board delivery across seven countries.',
      keyword: 'freight forwarder Piraeus',
    },
    el: {
      title: 'Διαμεταφορέας στον Πειραιά | Frontline',
      description: 'Διαμεταφορέας και ναυτιλιακό πρακτορείο με έδρα τον Πειραιά: θαλάσσιες, αεροπορικές και οδικές μεταφορές, εκτελωνισμός και εφοδιασμός πλοίων σε επτά χώρες.',
      keyword: 'διαμεταφορέας Πειραιά',
    },
  },
  about: {
    en: {
      title: 'About Frontline — Piraeus Freight Forwarder | Frontline',
      description: 'The story of a family-run Piraeus freight forwarder and ship agency running nine departments across seven countries with a 24/7 vessel operations desk.',
      keyword: 'Piraeus freight forwarder',
    },
    el: {
      title: 'Η Εταιρεία — Διαμεταφορέας Πειραιά | Frontline',
      description: 'Η ιστορία ενός οικογενειακού διαμεταφορέα και ναυτιλιακού πρακτορείου στον Πειραιά, με εννέα τμήματα σε επτά χώρες και 24/7 γραφείο πλοίων.',
      keyword: 'διαμεταφορέας Πειραιά',
    },
  },
  services: {
    en: {
      title: 'Freight Forwarding & Customs Clearance | Frontline',
      description: 'Sea, air and road forwarding, customs clearance, warehousing, ship supply, on-board delivery and project cargo: eight services on one operations file.',
      keyword: 'freight forwarding services Greece',
    },
    el: {
      title: 'Υπηρεσίες Διαμεταφοράς & Εκτελωνισμού | Frontline',
      description: 'Θαλάσσιες, αεροπορικές και οδικές μεταφορές, εκτελωνισμός, αποθήκευση, εφοδιασμός πλοίων και on-board παραδόσεις: οκτώ υπηρεσίες, ένας φάκελος.',
      keyword: 'υπηρεσίες διαμεταφοράς',
    },
  },
  network: {
    en: {
      title: 'Global Network — Seven Country Desks | Frontline',
      description: 'Frontline operates its own desks across seven countries, backed by a vetted agent network in 80+ ports worldwide: one accountable contact per port call.',
      keyword: 'global freight forwarding network',
    },
    el: {
      title: 'Παγκόσμιο Δίκτυο — Επτά Χώρες | Frontline',
      description: 'Η Frontline λειτουργεί ιδιόκτητα γραφεία σε επτά χώρες και δίκτυο ελεγμένων πρακτόρων σε 80+ λιμάνια παγκοσμίως: ένας υπεύθυνος για κάθε προσέγγιση.',
      keyword: 'παγκόσμιο δίκτυο μεταφορών',
    },
  },
  newsroom: {
    en: {
      title: 'Shipping News & Industry Insights | Frontline',
      description: 'Company announcements, customs and regulatory analysis, and shipping case studies written by the Frontline operations desk in Piraeus, Greece.',
      keyword: 'shipping news Greece',
    },
    el: {
      title: 'Νέα & Αναλύσεις Ναυτιλίας | Frontline',
      description: 'Εταιρικές ανακοινώσεις, αναλύσεις τελωνειακών και κανονιστικών θεμάτων και case studies ναυτιλίας από το γραφείο της Frontline στον Πειραιά.',
      keyword: 'νέα ναυτιλίας',
    },
  },
  contact: {
    en: {
      title: 'Contact — Piraeus Operations Desk | Frontline',
      description: 'Reach the Frontline 24/7 operations desk in Piraeus, Greece. Request a quote, book a vessel call, or open a forwarding file in any of seven countries.',
      keyword: 'contact freight forwarder Piraeus',
    },
    el: {
      title: 'Επικοινωνία — Γραφείο Πειραιά | Frontline',
      description: 'Επικοινωνήστε με το 24/7 γραφείο της Frontline στον Πειραιά. Ζητήστε προσφορά, κλείστε vessel call ή ανοίξτε φάκελο διαμεταφοράς σε επτά χώρες.',
      keyword: 'επικοινωνία διαμεταφορέα Πειραιά',
    },
  },
};

/* Default OG image — placeholder until real social card art is delivered */
const DEFAULT_OG_IMAGE = SITE_ORIGIN + '/assets/frontline-logo-dark.png';

/* ============================================================
   JSON-LD SCHEMA GENERATORS
   Runtime emits a single <script type="application/ld+json"
   id="fl-page-schema"> per page containing a @graph of every
   relevant schema type. Crawlers and LLMs read this directly.
   ============================================================ */

/* Reusable Organization node — referenced by @id from other graphs */
const ORG_NODE = {
  '@type': 'Organization',
  '@id': SITE_ORIGIN + '/#organization',
  name: 'FrontLine Forwarding & Agency Ltd',
  alternateName: 'FRONT LINE',
  url: SITE_ORIGIN + '/',
  logo: {
    '@type': 'ImageObject',
    url: SITE_ORIGIN + '/assets/frontline-logo-dark.png',
    width: 600,
    height: 200,
  },
  description: 'Piraeus-headquartered international freight forwarder and ship agency operating own desks across seven countries.',
  address: {
    '@type': 'PostalAddress',
    streetAddress: '45 Konstantinoupoleos Street',
    addressLocality: 'Piraeus',
    addressRegion: 'Attica',
    postalCode: '18540',
    addressCountry: 'GR',
  },
  contactPoint: [
    {
      '@type': 'ContactPoint',
      contactType: 'customer service',
      telephone: '+30-210-4200051',
      email: 'info@frontline-ltd.com',
      areaServed: ['GR', 'CY', 'NL', 'KR', 'JP', 'CN', 'SG'],
      availableLanguage: ['en', 'el'],
    },
  ],
};

/* LocalBusiness — homepage only. Inherits from Organization via @id. */
const LOCAL_BUSINESS_NODE = {
  '@type': 'LocalBusiness',
  '@id': SITE_ORIGIN + '/#localbusiness',
  name: 'FrontLine Forwarding & Agency Ltd — Piraeus Operations Desk',
  parentOrganization: { '@id': SITE_ORIGIN + '/#organization' },
  image: SITE_ORIGIN + '/assets/frontline-logo-dark.png',
  priceRange: '$$$',
  address: ORG_NODE.address,
  geo: {
    '@type': 'GeoCoordinates',
    latitude: 37.9420,
    longitude: 23.6478, // Piraeus port — approximate
  },
  openingHoursSpecification: [
    {
      '@type': 'OpeningHoursSpecification',
      dayOfWeek: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
      opens: '00:00',
      closes: '23:59',
      description: 'Open 24/7 — operations desk always on call',
    },
  ],
  telephone: '+30-210-4200051',
};

/* WebSite — homepage. No SearchAction: the site has no search endpoint,
   and schema must not advertise a feature that doesn't exist. */
const WEBSITE_NODE = {
  '@type': 'WebSite',
  '@id': SITE_ORIGIN + '/#website',
  url: SITE_ORIGIN + '/',
  name: 'FrontLine Forwarding & Agency Ltd',
  publisher: { '@id': SITE_ORIGIN + '/#organization' },
  inLanguage: ['en', 'el'],
};

/* Service node factory — used by services page graph */
function buildServiceNodes(lang) {
  const services = [
    { name: 'Sea Freight Forwarding', type: 'Sea freight forwarding', slug: 'sea-freight',
      description: 'FCL, LCL, NVOCC, breakbulk and project cargo via Piraeus and partner gateways.' },
    { name: 'Air Freight Forwarding', type: 'Air freight forwarding', slug: 'air-freight',
      description: 'Consolidation, charter, AOG, perishables and pharma cold chain on IATA-compliant operations.' },
    { name: 'Road & Combined Transport', type: 'Road freight and intermodal transport', slug: 'road-transport',
      description: 'FTL/LTL across Europe with intermodal rail-sea handoffs from Piraeus to Central Europe.' },
    { name: 'Customs Clearance', type: 'Customs brokerage and clearance', slug: 'customs-clearance',
      description: 'In-house licensed customs brokers, ICISnet integration, AEO procedures, transit and re-export filings.' },
    { name: 'Warehousing & Distribution', type: 'Warehousing, cross-dock and distribution', slug: 'warehousing',
      description: 'Bonded and non-bonded storage, cross-dock, kitting, labelling and last-mile distribution.' },
    { name: 'Ship Supply', type: 'Marine ship chandling and ship supply', slug: 'ship-supply',
      description: 'Marine chandling, provisions, deck and engine stores, technical supply against IMPA/ISSA codes.' },
    { name: 'On-Board Delivery', type: 'On-board delivery to vessels at anchorage and berth', slug: 'on-board-delivery',
      description: 'Anchorage and berth deliveries, launch coordination, spare parts and crew effects.' },
    { name: 'Project Cargo', type: 'Heavy-lift and project cargo movement', slug: 'project-cargo',
      description: 'Heavy-lift and out-of-gauge engineering, route surveys, permitting and on-site supervision.' },
  ];
  return services.map((s) => ({
    '@type': 'Service',
    '@id': SITE_ORIGIN + '/' + lang + '/services#' + s.slug,
    name: s.name,
    serviceType: s.type,
    provider: { '@id': SITE_ORIGIN + '/#organization' },
    areaServed: [
      { '@type': 'Country', name: 'Greece' },
      { '@type': 'Country', name: 'Cyprus' },
      { '@type': 'Country', name: 'Netherlands' },
      { '@type': 'Country', name: 'South Korea' },
      { '@type': 'Country', name: 'Japan' },
      { '@type': 'Country', name: 'China' },
      { '@type': 'Country', name: 'Singapore' },
    ],
    description: s.description,
  }));
}

/* BreadcrumbList — emits HOME → page (single-level for top-nav pages). */
function buildBreadcrumb(lang, page) {
  const homeName = lang === 'el' ? 'Αρχική' : 'Home';
  const pageNames = {
    en: { about: 'Our Story', services: 'Services', network: 'Network', newsroom: 'Newsroom', contact: 'Contact' },
    el: { about: 'Η Ιστορία Μας', services: 'Υπηρεσίες', network: 'Δίκτυο', newsroom: 'Νέα', contact: 'Επικοινωνία' },
  };
  const items = [{ '@type': 'ListItem', position: 1, name: homeName, item: buildAbsoluteUrl(lang, 'home') }];
  if (page !== 'home') {
    items.push({ '@type': 'ListItem', position: 2, name: pageNames[lang][page] || page, item: buildAbsoluteUrl(lang, page) });
  }
  return {
    '@type': 'BreadcrumbList',
    '@id': buildAbsoluteUrl(lang, page) + '#breadcrumb',
    itemListElement: items,
  };
}

/* Compose the @graph for a given page */
function buildPageSchema(lang, page) {
  const pageUrl = buildAbsoluteUrl(lang, page);
  const meta = (META[page] && META[page][lang]) || META.home[lang];
  const graph = [ORG_NODE];

  if (page === 'home') {
    graph.push(LOCAL_BUSINESS_NODE, WEBSITE_NODE);
    graph.push({
      '@type': 'WebPage',
      '@id': pageUrl + '#webpage',
      url: pageUrl,
      name: meta.title,
      description: meta.description,
      inLanguage: lang === 'el' ? 'el-GR' : 'en-GB',
      isPartOf: { '@id': SITE_ORIGIN + '/#website' },
      about: { '@id': SITE_ORIGIN + '/#organization' },
      primaryImageOfPage: DEFAULT_OG_IMAGE,
    });
  } else {
    graph.push(buildBreadcrumb(lang, page));
    graph.push({
      '@type': 'WebPage',
      '@id': pageUrl + '#webpage',
      url: pageUrl,
      name: meta.title,
      description: meta.description,
      inLanguage: lang === 'el' ? 'el-GR' : 'en-GB',
      isPartOf: { '@id': SITE_ORIGIN + '/#website' },
      breadcrumb: { '@id': pageUrl + '#breadcrumb' },
      about: { '@id': SITE_ORIGIN + '/#organization' },
    });
  }

  if (page === 'services') {
    graph.push(...buildServiceNodes(lang));
  }

  if (page === 'newsroom') {
    graph.push({
      '@type': 'CollectionPage',
      '@id': pageUrl + '#collection',
      name: meta.title,
      description: meta.description,
      inLanguage: lang === 'el' ? 'el-GR' : 'en-GB',
      isPartOf: { '@id': SITE_ORIGIN + '/#website' },
    });
  }

  if (page === 'contact') {
    graph.push(LOCAL_BUSINESS_NODE);
    graph.push({
      '@type': 'ContactPage',
      '@id': pageUrl + '#contactpage',
      name: meta.title,
      description: meta.description,
      mainEntity: { '@id': SITE_ORIGIN + '/#localbusiness' },
    });
  }

  return { '@context': 'https://schema.org', '@graph': graph };
}

function injectPageSchema(lang, page) {
  let s = document.head.querySelector('script#fl-page-schema');
  if (!s) {
    s = document.createElement('script');
    s.type = 'application/ld+json';
    s.id = 'fl-page-schema';
    document.head.appendChild(s);
  }
  s.textContent = JSON.stringify(buildPageSchema(lang, page), null, 2);
}

/* --------- Path helpers --------- */
function buildPath(lang, page) {
  const slug = (SLUGS[page] && SLUGS[page][lang]) || '';
  return slug ? `/${lang}/${slug}` : `/${lang}/`;
}

function buildAbsoluteUrl(lang, page) {
  return SITE_ORIGIN + buildPath(lang, page);
}

/* Parse a path like '/en/services' or '/el/ypiresies' → {lang, page}.
   Falls back to {lang: detected, page: 'home'} on unknowns. */
function parsePath(path) {
  // Strip leading hash if hash routing fallback
  let p = path || '/';
  if (p.startsWith('#')) p = p.slice(1);
  if (!p.startsWith('/')) p = '/' + p;

  const parts = p.split('/').filter(Boolean);
  let lang = 'en';
  let slug = '';

  if (parts[0] === 'en' || parts[0] === 'el') {
    lang = parts[0];
    slug = parts.slice(1).join('/').toLowerCase();
  } else {
    // No language prefix — keep current preference if any, default by browser
    const stored = (typeof localStorage !== 'undefined' && localStorage.getItem('fl_lang')) || null;
    lang = stored || detectBrowserLang();
    slug = parts.join('/').toLowerCase();
  }

  if (!slug) return { lang, page: 'home', needsRedirect: parts[0] !== 'en' && parts[0] !== 'el' };

  // Find page by matching slug for this language
  for (const key of PAGE_KEYS) {
    if (SLUGS[key][lang] === slug) return { lang, page: key, needsRedirect: false };
  }
  // Cross-language fallback (e.g. /en/etairia)
  for (const key of PAGE_KEYS) {
    if (SLUGS[key].en === slug || SLUGS[key].el === slug) return { lang, page: key, needsRedirect: true };
  }
  return { lang, page: 'home', needsRedirect: true };
}

function detectBrowserLang() {
  if (typeof navigator === 'undefined') return 'en';
  const langs = (navigator.languages || [navigator.language || 'en']);
  for (const l of langs) {
    if (l && l.toLowerCase().startsWith('el')) return 'el';
  }
  return 'en';
}

/* Use the History API on real production hosting only.
   In the preview/file environment we can't rewrite pathname without
   breaking asset URLs (the doc lives at /…/Something.html, not at /),
   so fall back to hash routing there. The static <head> still ships
   real /en/... canonicals + hreflangs for SEO consumers regardless. */
const SUPPORTS_HISTORY = (() => {
  try {
    if (typeof window === 'undefined' || !window.history || !window.history.pushState) return false;
    const loc = window.location;
    if (loc.protocol === 'file:') return false;
    // Document is served as a .html file (preview env, GitHub Pages, etc.)
    // Hosts that can route deep paths serve them at /en/about with no extension.
    if (/\.html?$/i.test(loc.pathname)) return false;
    // /serve/ path segment is a known preview-host marker
    if (loc.pathname.includes('/serve/')) return false;
    return true;
  } catch (e) { return false; }
})();

/* --------- Router hook --------- */
function useRouter() {
  const getInitialState = () => {
    if (typeof window === 'undefined') return { lang: 'en', page: 'home' };
    const path = SUPPORTS_HISTORY ? window.location.pathname : (window.location.hash || '/');
    const { lang, page, needsRedirect } = parsePath(path);
    if (needsRedirect && SUPPORTS_HISTORY) {
      const target = buildPath(lang, page);
      window.history.replaceState({ lang, page }, '', target);
    }
    return { lang, page };
  };

  const [state, setState] = useStateR(getInitialState);

  useEffectR(() => {
    const onPop = () => {
      const path = SUPPORTS_HISTORY ? window.location.pathname : window.location.hash;
      const parsed = parsePath(path);
      setState({ lang: parsed.lang, page: parsed.page });
    };
    if (SUPPORTS_HISTORY) {
      window.addEventListener('popstate', onPop);
      return () => window.removeEventListener('popstate', onPop);
    } else {
      window.addEventListener('hashchange', onPop);
      return () => window.removeEventListener('hashchange', onPop);
    }
  }, []);

  /* navigate to a page within current language */
  const navigate = useCallbackR((page, opts = {}) => {
    setState((s) => {
      const lang = opts.lang || s.lang;
      const target = buildPath(lang, page);
      if (SUPPORTS_HISTORY) {
        window.history.pushState({ lang, page }, '', target);
      } else {
        window.location.hash = target;
      }
      try { localStorage.setItem('fl_lang', lang); } catch (e) {}
      window.scrollTo({ top: 0, behavior: opts.smooth ? 'smooth' : 'auto' });
      return { lang, page };
    });
  }, []);

  /* swap language but keep current page */
  const switchLang = useCallbackR((lang) => {
    setState((s) => {
      const target = buildPath(lang, s.page);
      if (SUPPORTS_HISTORY) {
        window.history.pushState({ lang, page: s.page }, '', target);
      } else {
        window.location.hash = target;
      }
      try { localStorage.setItem('fl_lang', lang); } catch (e) {}
      return { lang, page: s.page };
    });
  }, []);

  return { ...state, navigate, switchLang };
}

/* --------- Document meta hook --------- */
function setOrCreateMeta(selector, attrs) {
  let el = document.head.querySelector(selector);
  if (!el) {
    el = document.createElement(selector.split('[')[0]);
    document.head.appendChild(el);
  }
  Object.keys(attrs).forEach((k) => el.setAttribute(k, attrs[k]));
  return el;
}

function useDocumentMeta(lang, page) {
  useEffectR(() => {
    const meta = (META[page] && META[page][lang]) || META.home[lang] || META.home.en;
    const url = buildAbsoluteUrl(lang, page);
    const ogLocale = lang === 'el' ? 'el_GR' : 'en_GB';
    const altLocale = lang === 'el' ? 'en_GB' : 'el_GR';

    // <html lang>
    document.documentElement.setAttribute('lang', lang === 'el' ? 'el' : 'en');

    // <title>
    document.title = meta.title;

    // description
    setOrCreateMeta('meta[name="description"]', { name: 'description', content: meta.description });
    setOrCreateMeta('meta[name="keywords"]', { name: 'keywords', content: meta.keyword });

    // canonical
    setOrCreateMeta('link[rel="canonical"]', { rel: 'canonical', href: url });

    // hreflang alternates — wipe stale ones first
    document.head.querySelectorAll('link[rel="alternate"][hreflang]').forEach((n) => n.remove());
    const enLink = document.createElement('link');
    enLink.rel = 'alternate'; enLink.hreflang = 'en'; enLink.href = buildAbsoluteUrl('en', page);
    document.head.appendChild(enLink);
    const elLink = document.createElement('link');
    elLink.rel = 'alternate'; elLink.hreflang = 'el'; elLink.href = buildAbsoluteUrl('el', page);
    document.head.appendChild(elLink);
    const xLink = document.createElement('link');
    xLink.rel = 'alternate'; xLink.hreflang = 'x-default'; xLink.href = buildAbsoluteUrl('en', page);
    document.head.appendChild(xLink);

    // Open Graph
    setOrCreateMeta('meta[property="og:type"]',        { property: 'og:type', content: page === 'newsroom' ? 'website' : 'website' });
    setOrCreateMeta('meta[property="og:site_name"]',   { property: 'og:site_name', content: 'FrontLine Forwarding & Agency Ltd' });
    setOrCreateMeta('meta[property="og:title"]',       { property: 'og:title', content: meta.title });
    setOrCreateMeta('meta[property="og:description"]', { property: 'og:description', content: meta.description });
    setOrCreateMeta('meta[property="og:url"]',         { property: 'og:url', content: url });
    setOrCreateMeta('meta[property="og:image"]',       { property: 'og:image', content: DEFAULT_OG_IMAGE });
    setOrCreateMeta('meta[property="og:locale"]',      { property: 'og:locale', content: ogLocale });

    // Wipe and rewrite alt locales
    document.head.querySelectorAll('meta[property="og:locale:alternate"]').forEach((n) => n.remove());
    const altOg = document.createElement('meta');
    altOg.setAttribute('property', 'og:locale:alternate'); altOg.setAttribute('content', altLocale);
    document.head.appendChild(altOg);

    // Twitter
    setOrCreateMeta('meta[name="twitter:card"]',        { name: 'twitter:card', content: 'summary_large_image' });
    setOrCreateMeta('meta[name="twitter:title"]',       { name: 'twitter:title', content: meta.title });
    setOrCreateMeta('meta[name="twitter:description"]', { name: 'twitter:description', content: meta.description });
    setOrCreateMeta('meta[name="twitter:image"]',       { name: 'twitter:image', content: DEFAULT_OG_IMAGE });

    // JSON-LD page graph
    injectPageSchema(lang, page);

  }, [lang, page]);
}

window.FL_ROUTER = { useRouter, useDocumentMeta, buildPath, buildAbsoluteUrl, parsePath, SLUGS, META };
