const { useState, useMemo, useRef, useEffect, useContext, createContext } = React;

/* --- minimal hash router (react-router-dom's CDN UMD build proved unreliable, so this is hand-rolled) --- */
const RouterCtx = createContext({ path: '/', params: {}, navigate: () => {} });

function getHashPath() {
  const h = window.location.hash.replace(/^#/, '');
  return h || '/';
}

function matchRoute(pattern, path) {
  const pSegs = pattern.split('/').filter(Boolean);
  const uSegs = path.split('/').filter(Boolean);
  if (pSegs.length !== uSegs.length) return null;
  const params = {};
  for (let i = 0; i < pSegs.length; i++) {
    if (pSegs[i].startsWith(':')) params[pSegs[i].slice(1)] = decodeURIComponent(uSegs[i]);
    else if (pSegs[i] !== uSegs[i]) return null;
  }
  return params;
}

function useNavigate() {
  const { navigate } = useContext(RouterCtx);
  return navigate;
}
function useParams() { return useContext(RouterCtx).params; }
function useLocation() { const { path } = useContext(RouterCtx); return { pathname: path }; }

function Link({ to, children, className, onClick }) {
  return <a href={'#' + to} className={className} onClick={onClick}>{children}</a>;
}
function NavLink({ to, end, children, className }) {
  const { path } = useContext(RouterCtx);
  const isActive = end ? path === to : (path === to || (to !== '/' && path.startsWith(to)));
  const cls = typeof className === 'function' ? className({ isActive }) : className;
  return <a href={'#' + to} className={cls}>{children}</a>;
}

function AppRouter({ routes }) {
  const [path, setPath] = useState(getHashPath());
  useEffect(() => {
    const onHash = () => setPath(getHashPath());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  useEffect(() => { window.scrollTo(0, 0); }, [path]);
  const navigate = (to) => { window.location.hash = to; };
  let matched = null, params = {};
  for (const r of routes) {
    const m = matchRoute(r.pattern, path);
    if (m) { matched = r; params = m; break; }
  }
  return (
    <RouterCtx.Provider value={{ path, params, navigate }}>
      {matched ? matched.element : <div className="max-w-[600px] mx-auto px-8 py-24 text-center text-[15px] text-[#667085]">Page not found.</div>}
    </RouterCtx.Provider>
  );
}

const BRAND = { name: 'FFwarder', tagline: 'Freight Forwarders, Found Faster.' };

const NEWS_ARTICLES = [
  { slug: 'red-sea-air-rates', title: 'Red Sea Disruptions Push Air Freight Rates Up 12% Into Europe', excerpt: 'Continued rerouting around the Cape of Good Hope is tightening ocean capacity, pushing more general cargo onto air — carriers report Shanghai–Frankfurt bookings at a 9-month high.', img: 'assets/air-freight.jpg', date: 'Sep 22, 2026', tag: 'Market Alert', body: 'Ocean carriers rerouting around the Cape of Good Hope have added 10–14 days to Asia–Europe transit times, and shippers with tight delivery windows are shifting volume onto air freight. DragonFly Air Cargo and three other platform forwarders report booking backlogs into early October on the Shanghai–Frankfurt and Shenzhen–Amsterdam lanes. Buyers with flexible ready dates may find better value locking in LCL space now before the shift fully absorbs available ocean capacity on alternate routings.' },
  { slug: 'eu-customs-nov1', title: 'New EU Customs Pre-Declaration Rules Start November 1', excerpt: 'ICS2 Release 3 extends advance cargo data requirements to road and rail — forwarders without updated systems risk clearance delays at Rotterdam and Hamburg.', img: 'assets/customs-port.jpg', date: 'Sep 18, 2026', tag: 'Regulatory', body: 'The EU’s Import Control System 2 (ICS2) enters its third rollout phase on November 1, requiring advance electronic cargo data for road and rail carriers in addition to the ocean and air modes already covered. Forwarders moving cargo through Rotterdam, Hamburg, or Antwerp should confirm their customs broker has ICS2 Release 3 connectivity in place — incomplete filings will be held at the border rather than cleared on arrival.' },
  { slug: 'ningbo-warehouse-capacity', title: 'Ningbo Bonded Warehouse Capacity Tightens Ahead of Peak Season', excerpt: 'Consolidation warehouses near Ningbo-Zhoushan port are reporting 85%+ utilization as exporters pre-build inventory for Q4 — book LCL space early.', img: 'assets/warehouse.jpg', date: 'Sep 10, 2026', tag: 'Capacity', body: 'With Q4 peak season approaching, bonded warehouse operators around Ningbo-Zhoushan are reporting utilization above 85%, the highest level since 2023. Several forwarders on the platform, including BlueWave Logistics and NordicLink Cargo, are advising customers to confirm LCL consolidation slots at least 10 days ahead of their ready date to avoid rolling to the following week’s sailing.' },
];

const TESTIMONIALS = [
  { company: 'Nordic Safety AB', person: 'Elin Johansson, Procurement Lead', quote: 'We used to email five forwarders and wait two days for quotes. Now we post one RFQ and have real numbers in under an hour.', initials: 'NS' },
  { company: 'Berlin Trade GmbH', person: 'Markus Weber, Logistics Manager', quote: 'The AI recommendation explained exactly why it picked a supplier over a cheaper one — that transparency is what got our team to trust the platform.', initials: 'BT' },
  { company: 'Tokyo Retail Supply Co.', person: 'Aiko Tanaka, Operations', quote: 'Being able to see a forwarder’s on-time rate before booking changed how we choose suppliers entirely.', initials: 'TR' },
];

const SPONSOR_ADS = [
  { label: 'Sponsored', title: 'Cargo Insurance from $0.15/kg', body: 'SafeShip covers loss and damage on every mode, quoted instantly at checkout.', cta: 'Get a Quote', color: '#0B7285', bg: '#E7F7F9' },
  { label: 'Sponsored', title: 'FF Trade Finance', body: 'Pay suppliers now, settle invoices in 60 days. No collateral for verified importers.', cta: 'Check Eligibility', color: '#7C3AED', bg: '#F3EEFF' },
];

const PRICING_PLANS = [
  { name: 'Free', price: '$0', period: '/month', audience: 'For forwarders getting started', features: ['Appear in Freight Directory search', 'Respond to matched RFQs (up to 10/mo)', 'Basic company profile', 'Standard support'], cta: 'Start Free', highlight: false },
  { name: 'Pro', price: '$89', period: '/month', audience: 'For active forwarders', features: ['Unlimited RFQ responses', 'AI Recommended placement eligibility', 'Priority Directory ranking', 'Rate card AI import & health alerts', 'Priority support'], cta: 'Upgrade to Pro', highlight: true },
  { name: 'Enterprise', price: 'Custom', period: '', audience: 'For large networks & agents', features: ['Everything in Pro', 'API access to quote & booking data', 'Dedicated account manager', 'Custom SLA & invoicing'], cta: 'Talk to Sales', highlight: false },
];

const FORWARDERS = [
  {
    slug: 'bluewave-logistics', name: 'BlueWave Logistics', short: 'BW', city: 'Ningbo', country: 'China',
    verified: 'verified', rating: 4.9, responseTime: '14 min', completed: 1286, onTime: 96, founded: 2011,
    lanes: ['Japan', 'Korea', 'Northern Europe'], services: ['Air Freight', 'LCL', 'DDP', 'Customs Clearance'],
    specialties: ['General Cargo', 'Amazon FBA'], certifications: ['FIATA', 'NVOCC', 'IATA Agent'],
    cover: 'assets/forwarder-cover.jpg',
    description: 'BlueWave Logistics has moved general cargo and Amazon FBA shipments out of Ningbo for over a decade, with the strongest response times on Japan and Northern Europe lanes on the platform.',
  },
  {
    slug: 'eastbridge-freight', name: 'EastBridge Freight', short: 'EB', city: 'Shanghai', country: 'China',
    verified: 'verified', rating: 4.8, responseTime: '22 min', completed: 947, onTime: 94, founded: 2014,
    lanes: ['Germany', 'Netherlands', 'France'], services: ['FCL', 'LCL', 'Rail Freight'],
    specialties: ['Textile', 'Electronics'], certifications: ['FIATA', 'Customs qualification'],
    cover: 'assets/port-felixstowe.jpg',
    description: 'EastBridge Freight specializes in FCL and rail solutions from Shanghai into Western Europe, with dedicated block-train capacity to Germany and the Netherlands.',
  },
  {
    slug: 'nordiclink-cargo', name: 'NordicLink Cargo', short: 'NL', city: 'Ningbo', country: 'China',
    verified: 'verified', rating: 4.7, responseTime: '19 min', completed: 612, onTime: 93, founded: 2016,
    lanes: ['Scandinavia', 'Baltics'], services: ['LCL', 'Door to Door'],
    specialties: ['General Cargo'], certifications: ['NVOCC'],
    cover: 'assets/port-miami.jpg',
    description: 'NordicLink Cargo built its business around Scandinavian LCL consolidation out of Ningbo, offering some of the most competitive door-to-door pricing into the Nordics.',
  },
  {
    slug: 'sinoglobal-forwarding', name: 'SinoGlobal Forwarding', short: 'SG', city: 'Guangzhou', country: 'China',
    verified: 'pending', rating: 4.6, responseTime: '31 min', completed: 388, onTime: 91, founded: 2019,
    lanes: ['Southeast Asia', 'Middle East'], services: ['Air Freight', 'FCL'],
    specialties: ['Oversized Cargo'], certifications: ['FIATA'],
    cover: 'assets/hero-port.jpg',
    description: 'SinoGlobal Forwarding is completing platform verification. It already serves Southeast Asia and Middle East lanes out of Guangzhou with an emphasis on oversized cargo.',
  },
  {
    slug: 'dragonfly-air-cargo', name: 'DragonFly Air Cargo', short: 'DF', city: 'Shenzhen', country: 'China',
    verified: 'verified', rating: 4.7, responseTime: '11 min', completed: 803, onTime: 97, founded: 2013,
    lanes: ['USA', 'Canada'], services: ['Air Freight', 'Express'],
    specialties: ['Battery Cargo', 'Electronics', 'Dangerous Goods'], certifications: ['IATA Agent', 'FIATA'],
    cover: 'assets/air-freight.jpg',
    description: 'DragonFly Air Cargo is the platform’s top-rated specialist for battery and electronics cargo out of Shenzhen, with in-house dangerous goods documentation.',
  },
  {
    slug: 'harborlink-logistics', name: 'HarborLink Logistics', short: 'HL', city: 'Qingdao', country: 'China',
    verified: 'verified', rating: 4.5, responseTime: '26 min', completed: 421, onTime: 90, founded: 2015,
    lanes: ['Northern Europe', 'UK'], services: ['FCL', 'LCL', 'Warehousing'],
    specialties: ['Automotive'], certifications: ['NVOCC', 'Customs qualification'],
    cover: 'assets/port-felixstowe.jpg',
    description: 'HarborLink Logistics runs FCL and LCL services out of Qingdao into Northern Europe and the UK, with bonded warehousing on both ends of the lane.',
  },
];

const ROUTES = [
  { slug: 'ningbo-to-tokyo', origin: 'Ningbo', destination: 'Tokyo', originCountry: 'China', destCountry: 'Japan', modes: ['Air', 'LCL', 'Express'], rateFrom: '$1.85/kg', transit: '3–5 days', activeForwarders: 14, cover: 'assets/tokyo-skyline.jpg',
    market: [ { mode: 'Air', range: '$1.80–$2.35/kg', transit: '3–5 days' }, { mode: 'Ocean LCL', range: '$38–$58/CBM', transit: '12–16 days' }, { mode: 'Express', range: '$3.80–$5.20/kg', transit: '2–3 days' } ],
    notes: 'Japan customs requires a commercial invoice, packing list and, for reflective/safety apparel, a certificate of compliance for the destination retailer.', cargo: ['General cargo', 'Amazon FBA', 'Apparel'] },
  { slug: 'ningbo-to-osaka', origin: 'Ningbo', destination: 'Osaka', originCountry: 'China', destCountry: 'Japan', modes: ['Air', 'LCL'], rateFrom: '$1.95/kg', transit: '3–6 days', activeForwarders: 9, cover: 'assets/tokyo-skyline.jpg',
    market: [ { mode: 'Air', range: '$1.90–$2.40/kg', transit: '3–6 days' }, { mode: 'Ocean LCL', range: '$40–$60/CBM', transit: '13–17 days' } ],
    notes: 'Similar documentation requirements to Tokyo; Osaka port congestion can add 1–2 days during peak season.', cargo: ['General cargo', 'Electronics'] },
  { slug: 'shanghai-to-hamburg', origin: 'Shanghai', destination: 'Hamburg', originCountry: 'China', destCountry: 'Germany', modes: ['LCL', 'FCL', 'Rail'], rateFrom: '$48/CBM', transit: '28–34 days', activeForwarders: 18, cover: 'assets/port-felixstowe.jpg',
    market: [ { mode: 'Ocean LCL', range: '$44–$58/CBM', transit: '28–34 days' }, { mode: 'Ocean FCL (20′)', range: '$1,150–$1,450', transit: '28–32 days' }, { mode: 'Rail', range: '$2,600–$3,100 / 40′', transit: '18–22 days' } ],
    notes: 'EU import requires an EORI number on file; rail is the fastest non-air option on this lane.', cargo: ['Textile', 'Electronics', 'Automotive parts'] },
  { slug: 'shenzhen-to-los-angeles', origin: 'Shenzhen', destination: 'Los Angeles', originCountry: 'China', destCountry: 'USA', modes: ['Air', 'FCL', 'Express'], rateFrom: '$3.20/kg', transit: '4–6 days', activeForwarders: 16, cover: 'assets/port-miami.jpg',
    market: [ { mode: 'Air', range: '$3.00–$3.60/kg', transit: '4–6 days' }, { mode: 'Ocean FCL (40′)', range: '$2,400–$2,900', transit: '16–20 days' } ],
    notes: 'Battery and electronics cargo needs UN38.3 documentation on hand before booking air freight.', cargo: ['Electronics', 'Battery Cargo'] },
  { slug: 'qingdao-to-rotterdam', origin: 'Qingdao', destination: 'Rotterdam', originCountry: 'China', destCountry: 'Netherlands', modes: ['FCL', 'LCL'], rateFrom: '$1,180/FCL', transit: '30–36 days', activeForwarders: 11, cover: 'assets/warehouse.jpg',
    market: [ { mode: 'Ocean FCL (20′)', range: '$1,180–$1,480', transit: '30–36 days' }, { mode: 'Ocean LCL', range: '$46–$60/CBM', transit: '31–37 days' } ],
    notes: 'Rotterdam is the standard gateway for onward European distribution; ask forwarders about bonded transshipment options.', cargo: ['Automotive', 'General cargo'] },
  { slug: 'ningbo-to-oslo', origin: 'Ningbo', destination: 'Oslo', originCountry: 'China', destCountry: 'Norway', modes: ['LCL'], rateFrom: '$62/CBM', transit: '35–42 days', activeForwarders: 7, cover: 'assets/hero-port.jpg',
    market: [ { mode: 'Ocean LCL', range: '$58–$72/CBM', transit: '35–42 days' } ],
    notes: 'Norway is outside the EU customs union — budget extra time for customs clearance versus EU Nordic ports.', cargo: ['Reflective Accessories', 'General cargo'] },
];

const DEMO_SHIPMENT = {
  customer: 'Nordic Safety AB', origin: 'Ningbo, China', destination: 'Tokyo, Japan', cargo: 'Reflective Safety Vests',
  cartons: 10, weight: '200 kg', volume: '0.96 CBM', ready: 'Oct 8, 2026', requirement: 'Delivery within 7 days',
};

const QUOTES = [
  { id: '1', tag: 'recommended', supplier: 'bluewave-logistics', supplierName: 'BlueWave Logistics', mode: 'Air Freight', total: 318, transit: '4–6 days',
    breakdown: [ ['Air freight', 250], ['Fuel surcharge', 18], ['Terminal handling', 12], ['Pickup', 20], ['Customs docs', 25], ['Platform fee', 8] ],
    score: 4.9, onTime: 96, avgResponse: '14 min', completed: 1286, badges: ['AI Recommended', 'Verified', 'Best Value'],
    schedule: { ready: 'Oct 8', pickup: 'Oct 8', departure: 'Oct 9', eta: 'Oct 12', delivery: 'Oct 13' },
    reason: '$107 cheaper than the fastest option, still inside your 7-day window, and BlueWave has a 96% on-time record on this exact lane.' },
  { id: '2', tag: 'cheapest', supplier: 'sinoglobal-forwarding', supplierName: 'SinoGlobal Forwarding', mode: 'Air Freight', total: 286, transit: '6–8 days',
    breakdown: [ ['Air freight', 228], ['Fuel surcharge', 16], ['Terminal handling', 10], ['Pickup', 18], ['Customs docs', 14] ],
    score: 4.6, onTime: 91, avgResponse: '31 min', completed: 388, badges: ['Cheapest'],
    schedule: { ready: 'Oct 8', pickup: 'Oct 9', departure: 'Oct 10', eta: 'Oct 15', delivery: 'Oct 16' },
    reason: 'Lowest total cost, but transit runs 2–4 days longer than your requested 7-day window.' },
  { id: '3', tag: 'fastest', supplier: 'dragonfly-air-cargo', supplierName: 'DragonFly Air Cargo', mode: 'Air Freight', total: 425, transit: '2–3 days',
    breakdown: [ ['Air freight', 340], ['Fuel surcharge', 24], ['Terminal handling', 15], ['Pickup', 22], ['Customs docs', 24] ],
    score: 4.7, onTime: 97, avgResponse: '11 min', completed: 803, badges: ['Fastest'],
    schedule: { ready: 'Oct 8', pickup: 'Oct 8', departure: 'Oct 8', eta: 'Oct 10', delivery: 'Oct 11' },
    reason: 'Fastest option on the lane — worth it only if the 7-day window is at risk.' },
];

const RFQS = [
  { id: '1', code: 'FRQ-260915-0182', origin: 'Ningbo', destination: 'Oslo', mode: 'Sea Freight / LCL', cargo: 'Reflective Accessories', weight: '860 kg', volume: '3.2 CBM', ready: 'Oct 12', deadlineLabel: '19h 24m', posted: '5h ago', mine: true, matched: 23, invited: 15, opened: 9,
    quotes: [
      { supplier: 'bluewave-logistics', supplierName: 'BlueWave Logistics', price: 1185, transit: '31 days', service: 'LCL + Delivery', validity: 'Oct 10', rating: 4.9, status: 'Recommended' },
      { supplier: 'nordiclink-cargo', supplierName: 'NordicLink Cargo', price: 1130, transit: '36 days', service: 'LCL', validity: 'Oct 9', rating: 4.7, status: 'Cheapest' },
      { supplier: 'eastbridge-freight', supplierName: 'EastBridge Freight', price: 1260, transit: '29 days', service: 'LCL Express', validity: 'Oct 11', rating: 4.8, status: 'Fastest' },
    ] },
  { id: '2', code: 'FRQ-260916-0091', origin: 'Ningbo', destination: 'Tokyo', mode: 'Air Freight', cargo: 'General Cargo', weight: '280 kg', volume: '1.1 CBM', ready: 'Oct 14', deadlineLabel: '6h left', posted: '2h ago', mine: false, matched: 12, invited: 8, opened: 4,
    quotes: [ { supplier: 'bluewave-logistics', supplierName: 'BlueWave Logistics', price: 340, transit: '4–6 days', service: 'Air + Pickup', validity: 'Oct 12', rating: 4.9, status: 'Recommended' } ] },
  { id: '3', code: 'FRQ-260916-0104', origin: 'Shanghai', destination: 'Hamburg', mode: 'Ocean / LCL', cargo: 'Textile Rolls', weight: '4.8 CBM', volume: '4.8 CBM', ready: 'Oct 20', deadlineLabel: '18h left', posted: '1h ago', mine: false, matched: 19, invited: 12, opened: 6,
    quotes: [] },
  { id: '4', code: 'FRQ-260916-0110', origin: 'Shenzhen', destination: 'Los Angeles', mode: 'Air / Battery Cargo', cargo: 'Lithium Battery Packs', weight: '620 kg', volume: '2.0 CBM', ready: 'Oct 16', deadlineLabel: '10h left', posted: '40m ago', mine: false, matched: 8, invited: 6, opened: 2,
    quotes: [] },
  { id: '5', code: 'FRQ-260917-0033', origin: 'Qingdao', destination: 'Rotterdam', mode: 'Ocean / FCL', cargo: 'Automotive Parts', weight: '1x40′', volume: '—', ready: 'Oct 25', deadlineLabel: '2d left', posted: '20m ago', mine: false, matched: 11, invited: 7, opened: 1,
    quotes: [] },
];

const SHIPMENTS = [
  { id: 'SHP-26090382', route: 'Ningbo → Tokyo', supplier: 'BlueWave Logistics', supplierSlug: 'bluewave-logistics', mode: 'Air', cargo: '200 kg · Reflective Vests', status: 'In Transit', etd: 'Oct 9', eta: 'Oct 12', total: 318,
    timelineStep: 5 },
  { id: 'SHP-26090211', route: 'Shanghai → Hamburg', supplier: 'EastBridge Freight', supplierSlug: 'eastbridge-freight', mode: 'LCL', cargo: '4.8 CBM · Textile', status: 'Delivered', etd: 'Sep 2', eta: 'Sep 30', total: 1260,
    timelineStep: 8 },
  { id: 'SHP-26090175', route: 'Ningbo → Oslo', supplier: 'NordicLink Cargo', supplierSlug: 'nordiclink-cargo', mode: 'LCL', cargo: '3.2 CBM · Accessories', status: 'Booked', etd: 'Oct 12', eta: 'Nov 18', total: 1130,
    timelineStep: 1 },
  { id: 'SHP-26089940', route: 'Shenzhen → Los Angeles', supplier: 'DragonFly Air Cargo', supplierSlug: 'dragonfly-air-cargo', mode: 'Air', cargo: '620 kg · Battery Cargo', status: 'Exception', etd: 'Sep 20', eta: 'Sep 24', total: 425,
    timelineStep: 4 },
];

const TIMELINE_STEPS = ['Booking confirmed', 'Pickup scheduled', 'Cargo received', 'Customs cleared', 'Departed', 'Arrived', 'Out for delivery', 'Delivered'];

const LIVE_MARKET = [
  { route: 'Ningbo → Tokyo', mode: 'Air', rate: '$1.85/kg', transit: '3–5 days' },
  { route: 'Shanghai → Hamburg', mode: 'LCL', rate: '$48/CBM', transit: '28–34 days' },
  { route: 'Shenzhen → Los Angeles', mode: 'Air', rate: '$3.20/kg', transit: '4–6 days' },
  { route: 'Ningbo → Oslo', mode: 'LCL', rate: '$62/CBM', transit: '35–42 days' },
];

const SUPPLIER_SERVICE_TYPES = ['空运', '海运 FCL', '海运 LCL', '铁运', '卡车运输', '仓储', '报关报检', 'DDP 一站式'];
const SUPPLIER_SPECIALTIES = ['电池货', '危险品', '超大件', '冷链', '贵重品', 'Amazon FBA'];
const SUPPLIER_CERTS = ['FIATA', 'NVOCC', 'IATA 代理资质', 'AEO 认证'];
const SUPPLIER_ORIGIN_PORTS = ['宁波', '上海', '深圳', '青岛', '广州', '厦门', '天津'];
const SUPPLIER_DEST_REGIONS = ['日本/韩国', '东南亚', '北美', '西欧', '北欧', '中东', '澳洲'];

const AI_CANNED_REPLIES = [
  'Based on your cargo size and delivery window, I found several matching forwarders and current rates — want me to open the comparison?',
  'That lane has 3 active instant rates and 12 verified forwarders. I can pull up quotes now, or post it as an RFQ if you’d like more competitive bids.',
  'I’d recommend LCL if your window is over 20 days — it typically runs 30–40% cheaper than air for cargo this size.',
];
const Icon = {
  Ship: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill="none" stroke={p.c||'currentColor'} strokeWidth="1.8"><path d="M2 17c1.5 1 3 1 4.5 0s3-1 4.5 0 3 1 4.5 0 3-1 4.5 0"/><path d="M2 12c1.5 1 3 1 4.5 0s3-1 4.5 0 3 1 4.5 0 3-1 4.5 0"/></svg>),
  Plane: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill={p.c||'currentColor'}><polygon points="3,12 21,4 14,12 21,20"/></svg>),
  Zap: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill={p.c||'currentColor'}><polygon points="13,2 3,14 11,14 10,22 21,9 13,9"/></svg>),
  Rail: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill="none" stroke={p.c||'currentColor'} strokeWidth="1.8"><rect x="4" y="6" width="16" height="10" rx="2"/><circle cx="8" cy="18" r="1.5" fill={p.c||'currentColor'} stroke="none"/><circle cx="16" cy="18" r="1.5" fill={p.c||'currentColor'} stroke="none"/></svg>),
  Truck: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill="none" stroke={p.c||'currentColor'} strokeWidth="1.8"><rect x="2" y="9" width="12" height="7"/><path d="M14 11h4l3 3v2h-7z"/><circle cx="6" cy="18" r="1.5" fill={p.c||'currentColor'} stroke="none"/><circle cx="17" cy="18" r="1.5" fill={p.c||'currentColor'} stroke="none"/></svg>),
  Home: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill="none" stroke={p.c||'currentColor'} strokeWidth="1.8"><path d="M4 11 12 4l8 7"/><path d="M6 10v9h12v-9"/></svg>),
  Check: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill="none" stroke={p.c||'currentColor'} strokeWidth="2.4"><path d="M8 12l2.5 2.5L16 9"/><circle cx="12" cy="12" r="9"/></svg>),
  Star: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill={p.c||'#F59E0B'}><polygon points="12,3 14.8,9.2 21.5,9.9 16.5,14.3 18,21 12,17.3 6,21 7.5,14.3 2.5,9.9 9.2,9.2"/></svg>),
  Sparkle: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill="none" stroke={p.c||'currentColor'} strokeWidth="2"><path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M18 6l-2.5 2.5M8.5 15.5 6 18"/></svg>),
  Search: (p) => (<svg viewBox="0 0 24 24" width={p.size||20} height={p.size||20} fill="none" stroke={p.c||'currentColor'} strokeWidth="2"><circle cx="10" cy="10" r="7"/><line x1="21" y1="21" x2="15.5" y2="15.5"/></svg>),
  ArrowRight: (p) => (<svg viewBox="0 0 24 24" width={p.size||16} height={p.size||16} fill="none" stroke={p.c||'currentColor'} strokeWidth="2"><line x1="4" y1="12" x2="20" y2="12"/><polyline points="14,6 20,12 14,18"/></svg>),
  Clock: (p) => (<svg viewBox="0 0 24 24" width={p.size||14} height={p.size||14} fill="none" stroke={p.c||'currentColor'} strokeWidth="2.4"><circle cx="12" cy="12" r="9"/><polyline points="12,7 12,12 16,14"/></svg>),
  Heart: (p) => (<svg viewBox="0 0 24 24" width={p.size||18} height={p.size||18} fill={p.filled ? (p.c||'#DC2626') : 'none'} stroke={p.c||'currentColor'} strokeWidth="1.8"><path d="M12 20s-7-4.4-9.5-8.8C.8 8 2 4.5 5.4 4c2-.3 3.6.6 4.6 2.2C11 4.6 12.6 3.7 14.6 4c3.4.5 4.6 4 3.9 7.2C16 15.6 12 20 12 20z"/></svg>),
  Send: (p) => (<svg viewBox="0 0 24 24" width={p.size||18} height={p.size||18} fill={p.c||'currentColor'}><path d="m2 2 20 10L2 22l4-10Z"/></svg>),
};

function ModeIcon({ mode, size, c }) {
  const m = (mode || '').toLowerCase();
  if (m.includes('air') || m.includes('express')) return m.includes('express') ? <Icon.Zap size={size} c={c||'#F59E0B'} /> : <Icon.Plane size={size} c={c||'#2563EB'} />;
  if (m.includes('rail')) return <Icon.Rail size={size} c={c} />;
  if (m.includes('truck') || m.includes('door')) return <Icon.Truck size={size} c={c} />;
  return <Icon.Ship size={size} c={c} />;
}

function VerifiedBadge({ tier }) {
  if (tier === 'verified') return (
    <span className="inline-flex items-center gap-1 bg-[#EFFBF1] text-[#16A34A] text-[11px] font-bold px-2 py-0.5 rounded-full">
      <Icon.Check size={11} c="#16A34A" /> Verified
    </span>);
  return <span className="inline-flex items-center bg-[#FFF7E8] text-[#B45309] text-[11px] font-bold px-2 py-0.5 rounded-full">Pending</span>;
}

function DeadlinePill({ label, urgent }) {
  const scheme = urgent ? { bg: '#FDECEC', c: '#DC2626' } : { bg: '#FFF7E8', c: '#B45309' };
  return (
    <span className="inline-flex items-center gap-1 text-[11px] font-bold px-2 py-0.5 rounded-full" style={{ background: scheme.bg, color: scheme.c }}>
      <Icon.Clock size={10} c={scheme.c} /> {label}
    </span>);
}

function AIReasonChip({ label, reason }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="inline-block">
      <button onClick={() => setOpen(!open)} className="inline-flex items-center gap-1.5 bg-[#EEF4FF] text-[#2563EB] text-[11px] font-bold px-2.5 py-1 rounded-full hover:bg-[#DCE8FB] transition-colors">
        <Icon.Sparkle size={11} /> {label}
      </button>
      {open && (
        <div className="mt-2 max-w-xs text-[12px] leading-relaxed text-[#344054] bg-[#F7F8FA] border border-[#E4E7EC] rounded-lg px-3 py-2">
          {reason}
          <div className="mt-1.5 text-[11px] text-[#98A2B3]">Not helpful? <span className="underline cursor-pointer">Tell us why</span></div>
        </div>
      )}
    </div>
  );
}

function Btn({ children, to, onClick, variant = 'primary', size = 'md', className = '', type }) {
  const sizes = { sm: 'text-[13px] px-3.5 py-2', md: 'text-[14px] px-5 py-2.5', lg: 'text-[15px] px-7 py-3.5' };
  const variants = {
    primary: 'bg-[#2563EB] text-white hover:bg-[#3B82F6] border border-transparent',
    outline: 'bg-white text-[#0B1F3A] border border-[#E4E7EC] hover:bg-[#EEF4FF] hover:border-[#2563EB]',
    dark: 'bg-[#0B1F3A] text-white hover:bg-[#14304F] border border-transparent',
    ghost: 'bg-transparent text-[#344054] hover:text-[#0B1F3A] border border-transparent',
  };
  const cls = `inline-flex items-center justify-center gap-1.5 rounded-lg font-bold cursor-pointer transition-colors whitespace-nowrap ${sizes[size]} ${variants[variant]} ${className}`;
  if (to) return <Link to={to} className={cls}>{children}</Link>;
  return <button type={type || 'button'} onClick={onClick} className={cls}>{children}</button>;
}

function Card({ children, className = '', hover = true }) {
  return <div className={`bg-white border border-[#E4E7EC] rounded-2xl ${hover ? 'transition-all hover:shadow-lg hover:-translate-y-0.5' : ''} ${className}`}>{children}</div>;
}

const NAV_ITEMS = [
  ['Home', '/'], ['AI Quote', '/quote'], ['RFQ Market', '/rfq'], ['Freight Directory', '/forwarders'],
  ['Routes', '/routes'], ['Shipments', '/shipments'], ['AI Assistant', '/ai'],
];

function TopBar() {
  const [lang, setLang] = useState('EN');
  return (
    <div className="bg-[#0B1F3A] text-[#B7C3DA] text-[12px]">
      <div className="max-w-[1360px] mx-auto px-8 h-8 flex items-center justify-between">
        <div className="flex items-center gap-4">
          <span className="tabnum">USD/CNY 7.14</span>
          <span className="tabnum hidden sm:inline">EUR/USD 1.09</span>
          <span className="hidden md:inline text-[#5A6B8C]">·</span>
          <span className="hidden md:inline">Ningbo-Zhoushan port: normal operations</span>
        </div>
        <div className="flex items-center gap-4">
          <Link to="/news" className="hover:text-white">Market News</Link>
          <Link to="/pricing" className="hover:text-white">Pricing</Link>
          <a href="#" className="hover:text-white">Help Center</a>
          <button onClick={() => setLang(lang === 'EN' ? '中文' : 'EN')} className="hover:text-white font-semibold">{lang}</button>
        </div>
      </div>
    </div>
  );
}

function Header() {
  const loc = useLocation();
  return (
    <div className="sticky top-0 z-30 bg-white">
      <TopBar />
      <div className="bg-white/95 backdrop-blur border-b border-[#E4E7EC]">
        <div className="max-w-[1360px] mx-auto px-8 h-[76px] flex items-center justify-between">
          <div className="flex items-center gap-10">
            <Link to="/" className="flex flex-col leading-none">
              <span className="text-[22px] font-extrabold text-[#0B1F3A] tracking-tight">FFwarder</span>
              <span className="text-[10px] font-medium text-[#667085] tracking-wide">FREIGHT FORWARDERS, FOUND FASTER.</span>
            </Link>
            <div className="hidden lg:flex items-center gap-7">
              {NAV_ITEMS.map(([label, href]) => (
                <NavLink key={href} to={href} end={href === '/'}
                  className={({ isActive }) => `text-[14px] font-medium transition-colors ${isActive ? 'text-[#0B1F3A] font-bold' : 'text-[#344054] hover:text-[#0B1F3A]'}`}>
                  {label}
                </NavLink>
              ))}
            </div>
          </div>
          <div className="flex items-center gap-3">
            <Link to="/login" className="text-[14px] font-semibold text-[#344054] hover:text-[#0B1F3A]">Sign In</Link>
            <Btn to="/login" variant="outline" size="sm">Sign Up</Btn>
            <Btn to="/quote" variant="primary" size="sm">Get a Quote</Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

function SponsorBanner({ ad }) {
  const a = ad || SPONSOR_ADS[0];
  return (
    <div className="rounded-2xl px-6 py-4 flex items-center justify-between gap-4 flex-wrap" style={{ background: a.bg }}>
      <div className="flex items-center gap-4">
        <span className="text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded-full bg-white/70" style={{ color: a.color }}>{a.label}</span>
        <div>
          <div className="text-[14px] font-bold" style={{ color: a.color }}>{a.title}</div>
          <div className="text-[12px] text-[#344054]">{a.body}</div>
        </div>
      </div>
      <button className="text-[12px] font-bold px-4 py-2 rounded-lg bg-white shadow-sm hover:shadow" style={{ color: a.color }}>{a.cta}</button>
    </div>
  );
}

function Footer() {
  const [email, setEmail] = useState('');
  const [subscribed, setSubscribed] = useState(false);
  return (
    <div className="bg-[#0B1F3A] px-8 pt-12 pb-7">
      <div className="max-w-[1360px] mx-auto">
        <div className="flex items-center justify-between flex-wrap gap-4 pb-8 mb-8 border-b border-white/10">
          <div>
            <div className="text-[16px] font-bold text-white mb-1">Get weekly freight market insights</div>
            <div className="text-[13px] text-[#98A2B3]">Rate trends, capacity alerts, and regulatory changes — straight to your inbox.</div>
          </div>
          {subscribed ? (
            <div className="text-[13px] font-semibold text-[#7CE0A3]">You’re subscribed — thanks!</div>
          ) : (
            <form onSubmit={e => { e.preventDefault(); if (email) setSubscribed(true); }} className="flex gap-2">
              <input required type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@company.com" className="bg-white/10 border border-white/20 rounded-lg px-3.5 py-2.5 text-[13px] text-white placeholder-[#7A89A8] outline-none focus:border-white/50 w-64" />
              <button type="submit" className="bg-white text-[#0B1F3A] font-bold text-[13px] px-4 py-2.5 rounded-lg">Subscribe</button>
            </form>
          )}
        </div>
        <div className="grid grid-cols-5 gap-8 pb-8 border-b border-white/10">
          <div>
            <div className="text-[20px] font-extrabold text-white mb-2">FFwarder</div>
            <div className="text-[13px] text-[#98A2B3] leading-relaxed max-w-xs mb-4">AI Quote + Instant Rates + Smart RFQ + Freight Directory + Supplier Marketplace + Shipment Management — one platform, both directions.</div>
            <div className="flex gap-3">
              {['X', 'in', 'f'].map(s => <div key={s} className="w-8 h-8 rounded-full bg-white/10 flex items-center justify-center text-[12px] font-bold text-white">{s}</div>)}
            </div>
          </div>
          <div className="flex flex-col gap-2.5">
            <span className="text-[12px] font-bold text-white tracking-wide mb-1">PRODUCT</span>
            <Link to="/quote" className="text-[13px] text-[#98A2B3] hover:text-white">AI Quote</Link>
            <Link to="/rfq" className="text-[13px] text-[#98A2B3] hover:text-white">RFQ Market</Link>
            <Link to="/forwarders" className="text-[13px] text-[#98A2B3] hover:text-white">Freight Directory</Link>
            <Link to="/routes" className="text-[13px] text-[#98A2B3] hover:text-white">Routes</Link>
            <Link to="/pricing" className="text-[13px] text-[#98A2B3] hover:text-white">Pricing</Link>
          </div>
          <div className="flex flex-col gap-2.5">
            <span className="text-[12px] font-bold text-white tracking-wide mb-1">FOR FORWARDERS</span>
            <Link to="/login" className="text-[13px] text-[#98A2B3] hover:text-white">Join as Supplier</Link>
            <Link to="/supplier/dashboard" className="text-[13px] text-[#98A2B3] hover:text-white">Supplier Dashboard</Link>
            <Link to="/supplier/rates" className="text-[13px] text-[#98A2B3] hover:text-white">Rate Management</Link>
          </div>
          <div className="flex flex-col gap-2.5">
            <span className="text-[12px] font-bold text-white tracking-wide mb-1">RESOURCES</span>
            <Link to="/news" className="text-[13px] text-[#98A2B3] hover:text-white">Market News</Link>
            <a href="#" className="text-[13px] text-[#98A2B3] hover:text-white">Help Center</a>
            <a href="#" className="text-[13px] text-[#98A2B3] hover:text-white">Incoterms Guide</a>
          </div>
          <div className="flex flex-col gap-2.5">
            <span className="text-[12px] font-bold text-white tracking-wide mb-1">COMPANY</span>
            <Link to="/about" className="text-[13px] text-[#98A2B3] hover:text-white">About</Link>
            <Link to="/trust-safety" className="text-[13px] text-[#98A2B3] hover:text-white">Trust &amp; Safety</Link>
            <Link to="/contact" className="text-[13px] text-[#98A2B3] hover:text-white">Contact</Link>
          </div>
        </div>
        <div className="pt-5 flex items-center justify-between flex-wrap gap-2">
          <div className="text-[12px] text-[#667085]">© 2026 FFwarder. All rights reserved.</div>
          <div className="text-[11px] text-[#4B5B75]">Photography: Wikimedia Commons contributors, various licenses.</div>
        </div>
      </div>
    </div>
  );
}

function CustomerLayout({ children }) {
  return (
    <div className="min-h-screen bg-white flex flex-col">
      <Header />
      <div className="flex-1">{children}</div>
      <Footer />
    </div>
  );
}

const SUPPLIER_NAV = [
  ['工作台', '/supplier/dashboard'], ['推荐询盘', '/supplier/dashboard'], ['RFQ 市场', '/supplier/dashboard'],
  ['报价管理', '/supplier/dashboard'], ['运价管理', '/supplier/rates'], ['订单管理', '/supplier/dashboard'],
  ['客户消息', '/supplier/dashboard'], ['公司主页', '/supplier/company'], ['数据分析', '/supplier/dashboard'], ['账户设置', '/supplier/dashboard'],
];

function SupplierLayout({ children, active }) {
  const navigate = useNavigate();
  return (
    <div className="min-h-screen bg-[#F7F8FA] flex">
      <div className="w-[232px] bg-[#0B1F3A] flex flex-col shrink-0">
        <div className="h-[64px] flex items-center px-6 border-b border-white/10">
          <span className="text-white font-extrabold text-[18px]">FFwarder</span>
          <span className="ml-2 text-[11px] text-[#98A2B3]">供应商后台</span>
        </div>
        <div className="flex-1 py-4">
          {SUPPLIER_NAV.map(([label, href], i) => (
            <div key={i} onClick={() => navigate(href)}
              className={`px-6 py-2.5 text-[14px] cursor-pointer transition-colors ${active === label ? 'bg-white/10 text-white font-bold border-r-2 border-[#2563EB]' : 'text-[#B7C3DA] hover:text-white hover:bg-white/5'}`}>
              {label}
            </div>
          ))}
        </div>
        <div className="p-4 border-t border-white/10">
          <Link to="/" className="text-[12px] text-[#98A2B3] hover:text-white">← 返回客户端</Link>
        </div>
      </div>
      <div className="flex-1 flex flex-col min-w-0">
        <div className="h-[64px] bg-white border-b border-[#E4E7EC] flex items-center justify-between px-8 shrink-0">
          <div className="text-[15px] font-bold text-[#101828]">{active}</div>
          <div className="flex items-center gap-3">
            <span className="text-[12px] bg-[#EEF4FF] text-[#2563EB] font-bold px-2.5 py-1 rounded-full">方案：Free</span>
            <div className="w-9 h-9 rounded-full bg-[#0B1F3A] text-white flex items-center justify-center text-[13px] font-bold">BW</div>
          </div>
        </div>
        <div className="flex-1 p-8 overflow-y-auto">{children}</div>
      </div>
    </div>
  );
}
function SectionTitle({ children, sub }) {
  return (
    <div className="mb-6">
      <h2 className="text-[28px] font-extrabold text-[#0B1F3A] m-0">{children}</h2>
      {sub && <p className="text-[14px] text-[#667085] mt-1.5 m-0">{sub}</p>}
    </div>
  );
}

function ForwarderCard({ f, featured }) {
  return (
    <Card className={`overflow-hidden flex flex-col ${featured ? 'ring-2 ring-[#F59E0B]' : ''}`}>
      <div className="relative h-28">
        <img src={f.cover} className="w-full h-full object-cover" alt={f.name} />
        <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent"></div>
        {featured && <span className="absolute top-2 left-2 bg-[#F59E0B] text-white text-[10px] font-bold px-2 py-0.5 rounded-full">Featured Partner</span>}
        <div className="absolute top-2 right-2"><VerifiedBadge tier={f.verified} /></div>
        <div className="absolute -bottom-4 left-4 w-10 h-10 rounded-lg bg-[#0B1F3A] text-white flex items-center justify-center text-[13px] font-extrabold border-2 border-white">{f.short}</div>
      </div>
      <div className="p-5 pt-6 flex flex-col gap-2 flex-1">
        <Link to={`/forwarders/${f.slug}`} className="text-[15px] font-bold text-[#101828] hover:text-[#2563EB]">{f.name}</Link>
        <div className="text-[13px] text-[#667085]">{f.city}, {f.country}</div>
        <div className="text-[12px] text-[#667085]">Lanes: {f.lanes.join(', ')}</div>
        <div className="flex items-center gap-1">
          <Icon.Star size={14} />
          <span className="text-[13px] font-bold text-[#101828] tabnum">{f.rating}</span>
          <span className="text-[12px] text-[#98A2B3]">· {f.responseTime} avg response</span>
        </div>
        <Btn to={`/forwarders/${f.slug}`} size="sm" className="mt-auto w-full">Request Quote</Btn>
      </div>
    </Card>
  );
}

function NewsCard({ a, compact }) {
  return (
    <Link to={`/news/${a.slug}`}>
      <Card className="overflow-hidden flex flex-col h-full">
        <div className={compact ? 'h-28' : 'h-40'}><img src={a.img} className="w-full h-full object-cover" alt={a.title} /></div>
        <div className="p-4 flex flex-col gap-1.5">
          <span className="text-[10px] font-bold text-[#2563EB] uppercase tracking-wide">{a.tag} · {a.date}</span>
          <span className={`font-bold text-[#101828] ${compact ? 'text-[13px]' : 'text-[15px]'}`}>{a.title}</span>
          {!compact && <span className="text-[13px] text-[#667085] leading-relaxed">{a.excerpt}</span>}
        </div>
      </Card>
    </Link>
  );
}

function HomePage() {
  const navigate = useNavigate();
  return (
    <div>
      {/* HERO */}
      <div className="relative overflow-hidden">
        <div className="absolute inset-0">
          <img src="assets/hero-port.jpg" className="w-full h-full object-cover" alt="Aerial view of a container port" />
          <div className="absolute inset-0 bg-gradient-to-r from-[#0B1F3A]/95 via-[#0B1F3Add]/80 to-[#0B1F3A]/40"></div>
        </div>
        <div className="relative max-w-[1360px] mx-auto px-8 pt-20 pb-24">
          <div className="grid grid-cols-2 gap-12 items-center">
            <div className="flex flex-col items-start gap-5">
              <div className="inline-flex items-center gap-1.5 bg-white/10 text-white text-[12px] font-bold px-3.5 py-1.5 rounded-full border border-white/20">
                <Icon.Sparkle size={14} /> AI-POWERED FREIGHT MARKETPLACE
              </div>
              <h1 className="text-[48px] leading-[1.12] font-extrabold text-white tracking-tight m-0">Compare Freight. Find Forwarders.<br/>Ship Smarter.</h1>
              <p className="text-[16px] leading-relaxed text-[#D6E0F0] max-w-md m-0">Instant rates, matched freight forwarders, RFQ bidding, and AI-powered logistics decisions — all in one place.</p>
              <div className="flex gap-9 mt-1">
                <div><div className="text-[24px] font-extrabold text-white tabnum">20+</div><div className="text-[12px] text-[#B7C3DA]">Verified forwarders</div></div>
                <div><div className="text-[24px] font-extrabold text-white tabnum">500+</div><div className="text-[12px] text-[#B7C3DA]">Active lanes</div></div>
                <div><div className="text-[24px] font-extrabold text-white tabnum">14 min</div><div className="text-[12px] text-[#B7C3DA]">Avg. quote response</div></div>
              </div>
            </div>
            <div className="hidden md:block"></div>
          </div>
        </div>
      </div>

      {/* QUOTE BOX (overlaps hero) */}
      <div className="max-w-[1360px] mx-auto px-8 -mt-14 relative z-10">
        <Card hover={false} className="p-6 shadow-xl">
          <div className="grid grid-cols-5 gap-3">
            {[['Origin', 'Ningbo, China'], ['Destination', 'Tokyo, Japan'], ['Cargo Details', 'General cargo'], ['Weight / Volume', '200 kg · 0.96 CBM'], ['Ready Date', 'Oct 8, 2026']].map(([label, val]) => (
              <div key={label} className="flex flex-col gap-1.5">
                <span className="text-[12px] font-semibold text-[#667085]">{label}</span>
                <div className="border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px] text-[#101828] tabnum">{val}</div>
              </div>
            ))}
          </div>
          <div className="flex items-center justify-between mt-4 gap-4 flex-wrap">
            <Btn onClick={() => navigate('/quote/results')} size="lg">Get Instant Quotes</Btn>
            <span className="text-[13px] text-[#98A2B3]">or describe your shipment in plain English —</span>
          </div>
          <div className="mt-3.5 bg-[#F7F8FA] border border-dashed border-[#E4E7EC] rounded-lg px-4 py-3.5 flex items-center gap-2.5">
            <Icon.Sparkle size={16} c="#667085" />
            <span className="text-[14px] text-[#667085] italic">"12 cartons from Ningbo to Tokyo, 280 kg, general cargo, need delivery within 7 days."</span>
          </div>
          <div className="flex gap-2.5 mt-3.5">
            <Btn to="/ai" variant="outline" size="sm">Ask AI</Btn>
            <Btn to="/rfq/new" variant="outline" size="sm">Post RFQ</Btn>
          </div>
        </Card>
      </div>

      {/* SPONSOR BANNER */}
      <div className="max-w-[1360px] mx-auto px-8 pt-8">
        <SponsorBanner ad={SPONSOR_ADS[0]} />
      </div>

      {/* TRANSPORT MODES */}
      <div className="max-w-[1360px] mx-auto px-8 pt-10 pb-4">
        <div className="grid grid-cols-6 gap-3.5">
          {[['Ocean Freight', <Icon.Ship c="#2563EB" size={22}/>], ['Air Freight', <Icon.Plane c="#2563EB" size={22}/>], ['Express', <Icon.Zap c="#F59E0B" size={22}/>], ['Rail Freight', <Icon.Rail c="#2563EB" size={22}/>], ['Trucking', <Icon.Truck c="#2563EB" size={22}/>], ['Door to Door', <Icon.Home c="#2563EB" size={22}/>]].map(([label, icon]) => (
            <Card key={label} className="px-3.5 py-4.5 flex flex-col items-center gap-2.5 cursor-pointer" >
              {icon}
              <span className="text-[13px] font-semibold text-[#101828]">{label}</span>
            </Card>
          ))}
        </div>
      </div>

      {/* WHY USE */}
      <div className="max-w-[1360px] mx-auto px-8 pt-10 pb-14">
        <SectionTitle>Why shippers use FFwarder</SectionTitle>
        <div className="grid grid-cols-4 gap-5">
          {[
            [<Icon.Check c="#2563EB"/>, 'Instant Rates', 'Compare available rates instantly, no waiting for email quotes.'],
            [<Icon.Search c="#2563EB"/>, 'Smart RFQ', 'Send one request to multiple matched forwarders at once.'],
            [<Icon.Check c="#2563EB"/>, 'Verified Forwarders', 'Find logistics providers by lane, service and proven track record.'],
            [<Icon.Sparkle c="#2563EB"/>, 'AI Recommendation', 'Get help choosing between price, transit time and service quality.'],
          ].map(([icon, title, body]) => (
            <Card key={title} className="p-6">
              <div className="w-10 h-10 rounded-[10px] bg-[#EEF4FF] flex items-center justify-center mb-3.5">{icon}</div>
              <div className="text-[16px] font-bold text-[#101828] mb-1.5">{title}</div>
              <div className="text-[14px] text-[#667085] leading-relaxed">{body}</div>
            </Card>
          ))}
        </div>
      </div>

      {/* TRUST BADGES */}
      <div className="max-w-[1360px] mx-auto px-8 pb-14">
        <div className="grid grid-cols-4 gap-5 bg-[#F7F8FA] rounded-2xl px-8 py-6">
          {[
            [<Icon.Check c="#16A34A"/>, 'Escrow-protected payments'],
            [<Icon.Check c="#16A34A"/>, 'Verified forwarders only'],
            [<Icon.Sparkle c="#16A34A"/>, '24/7 AI + human support'],
            [<Icon.Check c="#16A34A"/>, 'GDPR & data compliant'],
          ].map(([icon, label], i) => (
            <div key={i} className="flex items-center gap-2.5">
              <div className="w-8 h-8 rounded-full bg-white flex items-center justify-center shrink-0">{icon}</div>
              <span className="text-[13px] font-semibold text-[#344054]">{label}</span>
            </div>
          ))}
        </div>
      </div>

      {/* LIVE MARKET */}
      <div className="bg-[#F7F8FA] px-8 py-12">
        <div className="max-w-[1360px] mx-auto">
          <div className="flex items-center justify-between mb-5 gap-6 flex-wrap">
            <div className="flex items-center gap-6">
              <h2 className="text-[28px] font-extrabold text-[#0B1F3A] m-0">Live market snapshot</h2>
              <div className="flex items-center gap-2.5 bg-white border border-[#E4E7EC] rounded-[10px] px-3.5 py-2">
                <svg width="70" height="28" viewBox="0 0 70 28"><polyline points="0,20 10,22 20,14 30,17 40,9 50,12 60,5 70,7" fill="none" stroke="#16A34A" strokeWidth="2"/><circle cx="70" cy="7" r="2.5" fill="#16A34A"/></svg>
                <div><div className="text-[11px] text-[#98A2B3]">Air Rate Index</div><div className="text-[13px] font-bold text-[#16A34A]">▼ 4.2% this month</div></div>
              </div>
            </div>
            <Btn to="/routes" variant="outline" size="sm">Explore Routes <Icon.ArrowRight/></Btn>
          </div>
          <Card hover={false} className="overflow-hidden">
            <div className="grid grid-cols-4 px-6 py-3.5 bg-[#F7F8FA] border-b border-[#E4E7EC]">
              {['ROUTE', 'MODE', 'RATE FROM', 'TRANSIT'].map(h => <span key={h} className="text-[12px] font-bold text-[#667085]">{h}</span>)}
            </div>
            {LIVE_MARKET.map((r, i) => (
              <div key={i} className={`grid grid-cols-4 px-6 py-4 items-center ${i < LIVE_MARKET.length - 1 ? 'border-b border-[#E4E7EC]' : ''}`}>
                <span className="text-[14px] font-semibold text-[#101828]">{r.route}</span>
                <span className="text-[13px] text-[#344054]">{r.mode}</span>
                <span className="text-[14px] font-bold text-[#101828] tabnum">{r.rate}</span>
                <span className="text-[13px] text-[#344054]">{r.transit}</span>
              </div>
            ))}
          </Card>
        </div>
      </div>

      {/* MARKET NEWS */}
      <div className="max-w-[1360px] mx-auto px-8 py-14">
        <div className="flex items-center justify-between mb-6">
          <SectionTitle sub="Rate trends, capacity alerts, and regulatory changes from across the network.">Freight market news</SectionTitle>
          <Btn to="/news" variant="outline" size="sm">All News <Icon.ArrowRight/></Btn>
        </div>
        <div className="grid grid-cols-3 gap-5">
          {NEWS_ARTICLES.map(a => <NewsCard key={a.slug} a={a} />)}
        </div>
      </div>

      {/* FEATURED FORWARDERS */}
      <div className="bg-[#F7F8FA] px-8 py-14">
        <div className="max-w-[1360px] mx-auto">
          <SectionTitle>Featured freight forwarders</SectionTitle>
          <div className="grid grid-cols-4 gap-5">
            {FORWARDERS.slice(0, 4).map((f, i) => <ForwarderCard key={f.slug} f={f} featured={i === 0} />)}
          </div>
        </div>
      </div>

      {/* TESTIMONIALS */}
      <div className="max-w-[1360px] mx-auto px-8 py-14">
        <SectionTitle>What shippers are saying</SectionTitle>
        <div className="grid grid-cols-3 gap-5">
          {TESTIMONIALS.map(t => (
            <Card key={t.company} hover={false} className="p-6 flex flex-col gap-3">
              <div className="flex text-[#F59E0B]"><Icon.Star size={14}/><Icon.Star size={14}/><Icon.Star size={14}/><Icon.Star size={14}/><Icon.Star size={14}/></div>
              <p className="text-[14px] text-[#344054] leading-relaxed m-0">“{t.quote}”</p>
              <div className="flex items-center gap-2.5 mt-1">
                <div className="w-9 h-9 rounded-full bg-[#0B1F3A] text-white flex items-center justify-center text-[12px] font-bold">{t.initials}</div>
                <div>
                  <div className="text-[13px] font-bold text-[#101828]">{t.person}</div>
                  <div className="text-[12px] text-[#98A2B3]">{t.company}</div>
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>

      {/* RFQ PREVIEW */}
      <div className="bg-[#F7F8FA] px-8 py-14">
        <div className="max-w-[1360px] mx-auto">
          <div className="flex items-center justify-between mb-5">
            <div>
              <h2 className="text-[28px] font-extrabold text-[#0B1F3A] m-0 mb-1">Active RFQ marketplace</h2>
              <p className="text-[14px] text-[#667085] m-0">Post your freight request. Let forwarders compete for your business.</p>
            </div>
            <Btn to="/rfq">View RFQ Market</Btn>
          </div>
          <div className="grid grid-cols-3 gap-5">
            {RFQS.slice(0, 3).map(r => (
              <Link to={`/rfq/${r.id}`} key={r.id}>
                <Card className="p-5 flex flex-col gap-2">
                  <div className="flex items-center justify-between">
                    <span className="text-[15px] font-bold text-[#101828]">{r.origin} → {r.destination}</span>
                    <DeadlinePill label={r.deadlineLabel} urgent={r.deadlineLabel.includes('h')} />
                  </div>
                  <span className="text-[13px] text-[#667085]">{r.mode} · {r.weight}</span>
                  <span className="text-[12px] text-[#98A2B3]">{r.quotes.length || Math.max(1, r.opened - 3)} quote{(r.quotes.length || Math.max(1, r.opened - 3)) === 1 ? '' : 's'} received</span>
                </Card>
              </Link>
            ))}
          </div>
        </div>
      </div>

      {/* AI ASSISTANT PREVIEW */}
      <div className="max-w-[1360px] mx-auto px-8 py-14">
        <div className="grid grid-cols-2 gap-10 items-center">
          <div>
            <div className="inline-flex items-center gap-1.5 bg-[#EEF4FF] text-[#2563EB] text-[12px] font-bold px-3.5 py-1.5 rounded-full mb-4"><Icon.Sparkle size={14}/> AI FREIGHT ASSISTANT</div>
            <h2 className="text-[30px] font-extrabold text-[#0B1F3A] m-0 mb-3">Ask, and let the AI do the comparing</h2>
            <p className="text-[15px] leading-relaxed text-[#667085] max-w-sm mb-6">The assistant references your live shipments, quotes, and the supplier directory — not a generic chatbot.</p>
            <Btn to="/ai">Open AI Assistant</Btn>
          </div>
          <Card hover={false} className="p-5.5 flex flex-col gap-3.5">
            <div className="self-end max-w-[80%] bg-[#0B1F3A] text-white text-[14px] leading-relaxed px-4 py-3 rounded-2xl rounded-br-md">What is the best option for 2.5 CBM from Ningbo to Stockholm?</div>
            <div className="self-start max-w-[88%] bg-[#F7F8FA] text-[#101828] text-[14px] leading-relaxed px-4 py-3 rounded-2xl rounded-bl-md">
              Based on your cargo size and a 25-day delivery window, LCL is likely more economical. I found 8 active forwarders and 5 current rates.
              <div className="mt-2.5"><AIReasonChip label="Why this?" reason="LCL runs 30–40% cheaper than air for cargo under 3 CBM when the delivery window exceeds 20 days, and this lane has a 96% average on-time rate." /></div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function QuotePage() {
  const navigate = useNavigate();
  const [tab, setTab] = useState('guided');
  const [analyzing, setAnalyzing] = useState(false);
  const [parsed, setParsed] = useState(false);
  const [nlText, setNlText] = useState('10 cartons of reflective vests from Ningbo to Tokyo, 200 kg total, 0.96 CBM, ready October 8, must arrive within one week.');

  function analyze() {
    setAnalyzing(true);
    setTimeout(() => { setAnalyzing(false); setParsed(true); }, 1100);
  }

  return (
    <div className="max-w-[1360px] mx-auto px-8 py-12">
      <SectionTitle sub="Allow the AI to obtain instant rates or trigger a smart RFQ.">AI Quote</SectionTitle>
      <div className="grid grid-cols-2 gap-8 items-start">
        <div>
          <div className="flex gap-1 bg-[#F7F8FA] rounded-lg p-1 mb-5 w-fit">
            <button onClick={() => setTab('guided')} className={`px-4 py-2 rounded-md text-[13px] font-bold ${tab === 'guided' ? 'bg-white shadow text-[#0B1F3A]' : 'text-[#667085]'}`}>Guided Form</button>
            <button onClick={() => setTab('ai')} className={`px-4 py-2 rounded-md text-[13px] font-bold ${tab === 'ai' ? 'bg-white shadow text-[#0B1F3A]' : 'text-[#667085]'}`}>AI Natural Language</button>
          </div>
          {tab === 'guided' ? (
            <Card hover={false} className="p-6 flex flex-col gap-4">
              {[['Origin country / city', 'China · Ningbo'], ['Destination country / city', 'Japan · Tokyo'], ['Shipment type', 'General cargo'], ['Cartons / Gross weight', '10 cartons · 200 kg'], ['Total volume', '0.96 CBM'], ['Ready date', 'Oct 8, 2026'], ['Incoterm', 'FOB']].map(([label, val]) => (
                <div key={label}>
                  <div className="text-[12px] font-semibold text-[#667085] mb-1.5">{label}</div>
                  <div className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px]">{val}</div>
                </div>
              ))}
              <div className="flex gap-4 flex-wrap text-[13px] text-[#344054]">
                {['Pickup required', 'Customs clearance', 'Dangerous goods', 'Battery'].map((l, i) => (
                  <label key={l} className="flex items-center gap-1.5"><input type="checkbox" defaultChecked={i === 0} className="accent-[#2563EB]" /> {l}</label>
                ))}
              </div>
              <Btn onClick={analyze} size="lg" className="mt-1">Analyze Shipment</Btn>
            </Card>
          ) : (
            <Card hover={false} className="p-6 flex flex-col gap-4">
              <textarea value={nlText} onChange={e => setNlText(e.target.value)} rows={6} className="w-full border border-[#E4E7EC] rounded-lg px-3.5 py-3 text-[14px] resize-none focus:outline-none focus:border-[#2563EB]" placeholder="Describe what you want to ship…" />
              <Btn onClick={analyze} size="lg">Analyze Shipment</Btn>
            </Card>
          )}
        </div>
        <div>
          <div className="text-[13px] font-bold text-[#667085] mb-3 tracking-wide">AI PARSED SUMMARY</div>
          {analyzing && (
            <Card hover={false} className="p-8 flex flex-col items-center gap-3 text-center">
              <div className="w-8 h-8 border-[3px] border-[#E4E7EC] border-t-[#2563EB] rounded-full animate-spin"></div>
              <div className="text-[14px] text-[#667085]">AI is checking active rates and matching suitable forwarders…</div>
            </Card>
          )}
          {!analyzing && !parsed && (
            <Card hover={false} className="p-8 text-center text-[14px] text-[#98A2B3]">Fill in your shipment details, then analyze to see the AI summary here.</Card>
          )}
          {!analyzing && parsed && (
            <Card hover={false} className="p-6 flex flex-col gap-3">
              {[['Origin', 'Ningbo, China'], ['Destination', 'Tokyo, Japan'], ['Cargo', 'Reflective vests'], ['Cargo type', 'General cargo'], ['Weight', '200 kg'], ['Volume', '0.96 CBM'], ['Required transit', '≤ 7 days']].map(([k, v]) => (
                <div key={k} className="flex justify-between text-[14px]"><span className="text-[#667085]">{k}</span><span className="font-semibold text-[#101828]">{v}</span></div>
              ))}
              <div className="bg-[#FFF7E8] border border-[#F5D9A8] rounded-lg px-3.5 py-3 text-[13px] text-[#8A5A0A] flex flex-col gap-1">
                <span>“Do you need pickup from supplier?”</span>
                <span>“Do you need customs clearance in Japan?”</span>
              </div>
              <Btn onClick={() => navigate('/quote/results')} size="lg" className="mt-1">Confirm &amp; Find Rates</Btn>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

function QuoteCard({ q }) {
  const badgeColor = { 'AI Recommended': ['#EEF4FF', '#2563EB'], 'Verified': ['#EFFBF1', '#16A34A'], 'Best Value': ['#FFF7E8', '#B45309'], 'Cheapest': ['#EFFBF1', '#16A34A'], 'Fastest': ['#FDECEC', '#DC2626'] };
  return (
    <Card className="p-6 flex flex-col gap-4">
      <div className="flex items-start justify-between">
        <div>
          <Link to={`/forwarders/${q.supplier}`} className="text-[16px] font-bold text-[#101828] hover:text-[#2563EB]">{q.supplierName}</Link>
          <div className="flex items-center gap-1.5 mt-1"><ModeIcon mode={q.mode} size={15} /><span className="text-[13px] text-[#667085]">{q.mode}</span></div>
        </div>
        <div className="text-right">
          <div className="text-[24px] font-extrabold text-[#0B1F3A] tabnum">USD {q.total}</div>
          <div className="text-[12px] text-[#667085]">{q.transit}</div>
        </div>
      </div>
      <div className="flex flex-wrap gap-1.5">
        {q.badges.map(b => (
          <span key={b} className="text-[11px] font-bold px-2 py-0.5 rounded-full" style={{ background: badgeColor[b]?.[0] || '#F7F8FA', color: badgeColor[b]?.[1] || '#344054' }}>{b}</span>
        ))}
      </div>
      <div className="grid grid-cols-3 gap-2 text-[12px] text-[#667085] bg-[#F7F8FA] rounded-lg p-3">
        <div><div className="font-bold text-[#101828] tabnum">{q.onTime}%</div>on-time</div>
        <div><div className="font-bold text-[#101828] tabnum">{q.avgResponse}</div>avg response</div>
        <div><div className="font-bold text-[#101828] tabnum">{q.completed.toLocaleString()}</div>completed</div>
      </div>
      {q.tag === 'recommended' && <AIReasonChip label="AI Recommended · Best Value" reason={q.reason} />}
      <div className="flex gap-2 flex-wrap">
        <Btn to={`/quote/${q.id}`} size="sm">View Details</Btn>
        <Btn to={`/shipments/SHP-26090382`} variant="outline" size="sm">Book Now</Btn>
        <Btn to={`/forwarders/${q.supplier}`} variant="ghost" size="sm">Ask Supplier</Btn>
      </div>
    </Card>
  );
}

function QuoteResultsPage() {
  const navigate = useNavigate();
  const [tab, setTab] = useState('recommended');
  const [showRequestMore, setShowRequestMore] = useState(false);
  const filtered = tab === 'all' ? QUOTES : QUOTES.filter(q => q.tag === tab);
  return (
    <div className="max-w-[1360px] mx-auto px-8 py-12">
      <div className="mb-6">
        <div className="text-[13px] text-[#667085] mb-1">Quote Results</div>
        <h1 className="text-[26px] font-extrabold text-[#0B1F3A] m-0">Ningbo → Tokyo</h1>
        <div className="text-[13px] text-[#667085] mt-1">200 kg · 0.96 CBM · General Cargo · Ready Oct 8</div>
      </div>
      <div className="grid grid-cols-[1fr_320px] gap-8 items-start">
        <div>
          <div className="flex gap-1 bg-[#F7F8FA] rounded-lg p-1 mb-5 w-fit">
            {['recommended', 'cheapest', 'fastest', 'all'].map(t => (
              <button key={t} onClick={() => setTab(t)} className={`px-4 py-2 rounded-md text-[13px] font-bold capitalize ${tab === t ? 'bg-white shadow text-[#0B1F3A]' : 'text-[#667085]'}`}>{t}</button>
            ))}
          </div>
          <div className="flex flex-col gap-4">
            {filtered.map(q => <QuoteCard key={q.id} q={q} />)}
          </div>
        </div>
        <div className="flex flex-col gap-4 sticky top-24">
          <Card hover={false} className="p-5">
            <div className="text-[12px] font-bold text-[#667085] tracking-wide mb-2.5">AI RECOMMENDATION</div>
            <p className="text-[13px] leading-relaxed text-[#344054] m-0 mb-4">“BlueWave Logistics offers the best balance of cost and transit time. It is $107 cheaper than the fastest option while still meeting your requested delivery window.”</p>
            <div className="flex flex-col gap-2">
              <Btn to="/quote/1" className="w-full">Book Recommended</Btn>
              <Btn onClick={() => setShowRequestMore(true)} variant="outline" className="w-full">Request More Quotes</Btn>
              <Btn to="/rfq/new" variant="ghost" className="w-full">Post as RFQ</Btn>
            </div>
          </Card>
          {showRequestMore && (
            <Card hover={false} className="p-5">
              <div className="text-[15px] font-bold text-[#101828] mb-1">18 matched freight forwarders found</div>
              <div className="text-[12px] text-[#667085] mb-3">Matched by route expertise, cargo compatibility, response quality and rating.</div>
              <Btn onClick={() => navigate('/rfq/1')} className="w-full">Send RFQ to 15 Matched</Btn>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

function QuoteDetailPage() {
  const { id } = useParams();
  const q = QUOTES.find(x => x.id === id) || QUOTES[0];
  const f = FORWARDERS.find(x => x.slug === q.supplier);
  return (
    <div className="max-w-[1000px] mx-auto px-8 py-12">
      <div className="mb-6">
        <h1 className="text-[26px] font-extrabold text-[#0B1F3A] m-0">Ningbo → Tokyo</h1>
        <div className="text-[14px] text-[#667085] mt-1">{q.mode} · Supplier: <Link to={`/forwarders/${q.supplier}`} className="text-[#2563EB] font-semibold">{q.supplierName}</Link></div>
      </div>
      <div className="grid grid-cols-[1fr_300px] gap-8 items-start">
        <div className="flex flex-col gap-6">
          <Card hover={false} className="p-6">
            <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-3">COST BREAKDOWN</div>
            {q.breakdown.map(([label, val]) => (
              <div key={label} className="flex justify-between py-2 border-b border-[#F1F3F6] text-[14px]"><span className="text-[#344054]">{label}</span><span className="font-semibold text-[#101828] tabnum">${val}</span></div>
            ))}
            <div className="flex justify-between pt-3 text-[16px] font-extrabold text-[#0B1F3A]"><span>Estimated total</span><span className="tabnum">USD {q.total}</span></div>
          </Card>
          <Card hover={false} className="p-6">
            <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-3">SCHEDULE</div>
            <div className="grid grid-cols-5 gap-3 text-center">
              {Object.entries(q.schedule).map(([k, v]) => (
                <div key={k}><div className="text-[11px] text-[#98A2B3] capitalize mb-1">{k}</div><div className="text-[13px] font-bold text-[#101828]">{v}</div></div>
              ))}
            </div>
          </Card>
          <Card hover={false} className="p-6">
            <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-3">CONDITIONS</div>
            <ul className="m-0 pl-5 text-[13px] text-[#344054] flex flex-col gap-1.5">
              <li>General cargo only</li><li>Chargeable weight subject to final measurement</li><li>Rate valid until Oct 10</li><li>Space subject to carrier confirmation</li>
            </ul>
          </Card>
        </div>
        <div className="flex flex-col gap-4 sticky top-24">
          <Card hover={false} className="p-5">
            <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-3">SUPPLIER SNAPSHOT</div>
            <div className="flex flex-col gap-2 text-[13px]">
              <div className="flex justify-between"><span className="text-[#667085]">Rating</span><span className="font-bold">{f.rating}</span></div>
              <div className="flex justify-between"><span className="text-[#667085]">On-time</span><span className="font-bold">{f.onTime}%</span></div>
              <div className="flex justify-between"><span className="text-[#667085]">Founded</span><span className="font-bold">{f.founded}</span></div>
              <div className="flex justify-between"><span className="text-[#667085]">Completed</span><span className="font-bold">{f.completed.toLocaleString()}</span></div>
            </div>
            <div className="flex flex-col gap-2 mt-4">
              <Btn to="/shipments/SHP-26090382" className="w-full">Book Shipment</Btn>
              <Btn variant="outline" className="w-full">Request Clarification</Btn>
              <Btn to={`/forwarders/${q.supplier}`} variant="ghost" className="w-full">View Supplier Profile</Btn>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function RFQMarketPage() {
  const [onlyMine, setOnlyMine] = useState(false);
  const list = onlyMine ? RFQS.filter(r => r.mine) : RFQS;
  return (
    <div>
      <div className="bg-[#0B1F3A] px-8 py-14">
        <div className="max-w-[1360px] mx-auto text-center">
          <h1 className="text-[34px] font-extrabold text-white m-0 mb-3">Post Your Freight Request. Let Forwarders Compete for Your Business.</h1>
          <div className="flex justify-center gap-3 mt-5">
            <Btn to="/rfq/new" size="lg">Post an RFQ</Btn>
            <Btn onClick={() => setOnlyMine(!onlyMine)} variant="outline" size="lg" className="!bg-white/10 !text-white !border-white/30 hover:!bg-white/20">{onlyMine ? 'View All RFQs' : 'View My RFQs'}</Btn>
          </div>
        </div>
      </div>
      <div className="max-w-[1360px] mx-auto px-8 pt-8">
        <SponsorBanner ad={SPONSOR_ADS[0]} />
      </div>
      <div className="max-w-[1360px] mx-auto px-8 py-10">
        <div className="grid grid-cols-3 gap-5">
          {list.map(r => (
            <Link to={`/rfq/${r.id}`} key={r.id}>
              <Card className="p-5 flex flex-col gap-2">
                <div className="flex items-center justify-between">
                  <span className="text-[12px] font-bold text-[#98A2B3] tabnum">#{r.code}</span>
                  <DeadlinePill label={r.deadlineLabel} urgent={r.deadlineLabel.includes('h')} />
                </div>
                <span className="text-[16px] font-bold text-[#101828]">{r.origin} → {r.destination}</span>
                <span className="text-[13px] text-[#667085]">{r.mode}</span>
                <span className="text-[13px] text-[#344054]">{r.weight} / {r.volume} · Ready {r.ready}</span>
                <div className="flex items-center justify-between mt-1 text-[12px] text-[#98A2B3]">
                  <span>{r.quotes.length} quote{r.quotes.length === 1 ? '' : 's'} received</span><span>Posted {r.posted}</span>
                </div>
              </Card>
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}

const RFQ_STEPS = ['Origin & Destination', 'Cargo Details', 'Shipping Requirements', 'Quote Preference', 'Supplier Reach'];

function PostRFQPage() {
  const navigate = useNavigate();
  const [step, setStep] = useState(0);
  const [preference, setPreference] = useState('Best balance');
  const [reach, setReach] = useState('Both');
  return (
    <div className="max-w-[760px] mx-auto px-8 py-12">
      <SectionTitle sub="A wizard for publishing a freight request to the marketplace.">Post an RFQ</SectionTitle>
      <div className="flex items-center gap-2 mb-8">
        {RFQ_STEPS.map((s, i) => (
          <div key={s} className="flex items-center gap-2 flex-1">
            <div className={`w-7 h-7 rounded-full flex items-center justify-center text-[12px] font-bold shrink-0 ${i <= step ? 'bg-[#2563EB] text-white' : 'bg-[#F1F3F6] text-[#98A2B3]'}`}>{i + 1}</div>
            {i < RFQ_STEPS.length - 1 && <div className={`flex-1 h-0.5 ${i < step ? 'bg-[#2563EB]' : 'bg-[#E4E7EC]'}`}></div>}
          </div>
        ))}
      </div>
      <Card hover={false} className="p-7 min-h-[320px] flex flex-col">
        <div className="text-[18px] font-bold text-[#101828] mb-5">{RFQ_STEPS[step]}</div>
        <div className="flex-1">
          {step === 0 && (
            <div className="grid grid-cols-2 gap-4">
              <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">Origin</div><div className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px]">Ningbo, China</div></div>
              <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">Destination</div><div className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px]">Oslo, Norway</div></div>
            </div>
          )}
          {step === 1 && (
            <div className="grid grid-cols-2 gap-4">
              <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">Cargo</div><div className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px]">Reflective Accessories</div></div>
              <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">Weight / Volume</div><div className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px]">860 kg · 3.2 CBM</div></div>
            </div>
          )}
          {step === 2 && (
            <div className="flex flex-col gap-3 text-[13px] text-[#344054]">
              {['Pickup required', 'Delivery required', 'Customs clearance required', 'Dangerous goods'].map((l, i) => (
                <label key={l} className="flex items-center gap-2"><input type="checkbox" defaultChecked={i < 2} className="accent-[#2563EB]" /> {l}</label>
              ))}
            </div>
          )}
          {step === 3 && (
            <div className="flex flex-col gap-2">
              {['Cheapest', 'Fastest', 'Best balance', 'Door to door', 'DDP', 'Direct service preferred'].map(p => (
                <label key={p} className="flex items-center gap-2 text-[14px]"><input type="radio" name="pref" checked={preference === p} onChange={() => setPreference(p)} className="accent-[#2563EB]" /> {p}</label>
              ))}
            </div>
          )}
          {step === 4 && (
            <div className="flex flex-col gap-3">
              {['Public RFQ Marketplace', 'Invite matched suppliers only', 'Both'].map(r => (
                <label key={r} className="flex items-center gap-2 text-[14px]"><input type="radio" name="reach" checked={reach === r} onChange={() => setReach(r)} className="accent-[#2563EB]" /> {r}</label>
              ))}
              <div className="mt-3 bg-[#EEF4FF] text-[#2563EB] text-[13px] font-semibold rounded-lg px-3.5 py-3 flex items-center gap-2"><Icon.Sparkle size={15}/> We found 23 suitable freight forwarders for this request.</div>
            </div>
          )}
        </div>
        <div className="flex justify-between mt-6">
          <Btn variant="outline" onClick={() => setStep(s => Math.max(0, s - 1))} className={step === 0 ? 'invisible' : ''}>Back</Btn>
          {step < RFQ_STEPS.length - 1
            ? <Btn onClick={() => setStep(s => s + 1)}>Next</Btn>
            : <Btn onClick={() => navigate('/rfq/1')}>Publish RFQ</Btn>}
        </div>
      </Card>
    </div>
  );
}

function RFQDetailPage() {
  const { id } = useParams();
  const r = RFQS.find(x => x.id === id) || RFQS[0];
  return (
    <div className="max-w-[1100px] mx-auto px-8 py-12">
      <div className="mb-2 text-[13px] font-bold text-[#98A2B3] tabnum">RFQ #{r.code}</div>
      <h1 className="text-[26px] font-extrabold text-[#0B1F3A] m-0 mb-6">{r.origin} → {r.destination}</h1>
      <div className="grid grid-cols-4 gap-4 mb-8">
        {[['Cargo', r.cargo], ['Mode', r.mode], ['Weight / Volume', `${r.weight} / ${r.volume}`], ['Ready', r.ready]].map(([k, v]) => (
          <Card key={k} hover={false} className="p-4"><div className="text-[11px] text-[#98A2B3] mb-1">{k}</div><div className="text-[14px] font-bold text-[#101828]">{v}</div></Card>
        ))}
      </div>
      <div className="grid grid-cols-4 gap-4 mb-8">
        {[['Matched', r.matched], ['Invited', r.invited], ['Opened', r.opened], ['Quoted', r.quotes.length]].map(([k, v]) => (
          <div key={k} className="text-center"><div className="text-[22px] font-extrabold text-[#0B1F3A] tabnum">{v}</div><div className="text-[12px] text-[#667085]">{k}</div></div>
        ))}
      </div>
      <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-3">RECEIVED QUOTES</div>
      {r.quotes.length === 0 ? (
        <Card hover={false} className="p-10 text-center text-[14px] text-[#98A2B3]">No quotes yet — {r.opened} of {r.invited} invited forwarders have opened this RFQ.</Card>
      ) : (
        <Card hover={false} className="overflow-hidden">
          <div className="grid grid-cols-6 px-5 py-3 bg-[#F7F8FA] border-b border-[#E4E7EC] text-[11px] font-bold text-[#667085]">
            <span>SUPPLIER</span><span>PRICE</span><span>TRANSIT</span><span>SERVICE</span><span>RATING</span><span>STATUS</span>
          </div>
          {r.quotes.map((q, i) => (
            <div key={i} className={`grid grid-cols-6 px-5 py-3.5 items-center text-[13px] ${i < r.quotes.length - 1 ? 'border-b border-[#F1F3F6]' : ''}`}>
              <Link to={`/forwarders/${q.supplier}`} className="font-semibold text-[#101828] hover:text-[#2563EB]">{q.supplierName}</Link>
              <span className="font-bold tabnum">${q.price}</span>
              <span className="text-[#344054]">{q.transit}</span>
              <span className="text-[#344054]">{q.service}</span>
              <span className="flex items-center gap-1"><Icon.Star size={13}/>{q.rating}</span>
              <span className={`text-[11px] font-bold px-2 py-0.5 rounded-full w-fit ${q.status === 'Recommended' ? 'bg-[#EEF4FF] text-[#2563EB]' : q.status === 'Cheapest' ? 'bg-[#EFFBF1] text-[#16A34A]' : 'bg-[#FDECEC] text-[#DC2626]'}`}>{q.status}</span>
            </div>
          ))}
        </Card>
      )}
      {r.quotes.length > 0 && (
        <div className="flex gap-3 mt-6">
          <Btn to="/shipments/SHP-26090382">Select Supplier</Btn>
          <Btn variant="outline">Compare</Btn>
          <Btn variant="ghost">Message</Btn>
          <Btn variant="ghost">Shortlist</Btn>
        </div>
      )}
    </div>
  );
}

function DirectoryPage() {
  const [q, setQ] = useState('');
  const filtered = FORWARDERS.filter(f => (f.name + f.city + f.lanes.join(' ') + f.services.join(' ')).toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="max-w-[1360px] mx-auto px-8 py-12">
      <div className="text-center mb-8">
        <h1 className="text-[32px] font-extrabold text-[#0B1F3A] m-0 mb-2">Find the Right Freight Forwarder</h1>
        <p className="text-[15px] text-[#667085] m-0">Search by location, route, service, cargo expertise, or ask AI to recommend suppliers.</p>
      </div>
      <div className="max-w-[640px] mx-auto flex flex-col gap-3 mb-8">
        <div className="flex items-center gap-2 border border-[#E4E7EC] rounded-lg px-4 py-3">
          <Icon.Search size={17} c="#98A2B3" />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search freight forwarders, routes, services, cities…" className="flex-1 outline-none text-[14px]" />
        </div>
        <div className="flex items-center gap-2 border border-dashed border-[#E4E7EC] rounded-lg px-4 py-3 bg-[#F7F8FA]">
          <Icon.Sparkle size={16} c="#667085" />
          <span className="text-[13px] text-[#667085] italic">e.g. "I need a forwarder experienced in shipping lithium battery cargo from Shenzhen to Germany."</span>
        </div>
      </div>
      <div className="flex flex-wrap gap-2 justify-center mb-8">
        {['Air Freight', 'Ocean Freight', 'FCL', 'LCL', 'DDP', 'Customs', 'Battery Cargo', 'Amazon FBA'].map(f => (
          <span key={f} className="text-[12px] font-semibold px-3 py-1.5 rounded-full border border-[#E4E7EC] text-[#344054] hover:border-[#2563EB] hover:text-[#2563EB] cursor-pointer" onClick={() => setQ(f)}>{f}</span>
        ))}
      </div>
      <div className="mb-8"><SponsorBanner ad={SPONSOR_ADS[1]} /></div>
      <div className="grid grid-cols-3 gap-5">
        {filtered.map((f, i) => <ForwarderCard key={f.slug} f={f} featured={i === 0 && !q} />)}
        {filtered.length === 0 && <div className="col-span-3 text-center text-[14px] text-[#98A2B3] py-10">No forwarders match "{q}".</div>}
      </div>
    </div>
  );
}

function ForwarderProfilePage() {
  const { slug } = useParams();
  const f = FORWARDERS.find(x => x.slug === slug) || FORWARDERS[0];
  const [tab, setTab] = useState('Overview');
  const [fav, setFav] = useState(false);
  const tabs = ['Overview', 'Services', 'Routes', 'Rates', 'Reviews', 'Company Info'];
  return (
    <div>
      <div className="h-[220px] relative">
        <img src={f.cover} className="w-full h-full object-cover" alt={f.name} />
        <div className="absolute inset-0 bg-gradient-to-t from-[#0B1F3A]/90 to-transparent"></div>
      </div>
      <div className="max-w-[1100px] mx-auto px-8">
        <div className="-mt-14 relative flex items-end justify-between flex-wrap gap-4 mb-8">
          <div className="flex items-end gap-4">
            <div className="w-24 h-24 rounded-2xl bg-[#0B1F3A] text-white flex items-center justify-center text-[28px] font-extrabold border-4 border-white shadow-lg">{f.short}</div>
            <div className="pb-1">
              <div className="flex items-center gap-2"><h1 className="text-[24px] font-extrabold text-[#101828] m-0">{f.name}</h1><VerifiedBadge tier={f.verified} /></div>
              <div className="text-[13px] text-[#667085] mt-1">{f.city}, {f.country} · <Icon.Star size={13}/> {f.rating} · Member since {f.founded} · {f.responseTime} avg response</div>
            </div>
          </div>
          <div className="flex gap-2 pb-1">
            <Btn to="/quote">Request Quote</Btn>
            <Btn variant="outline">Send Message</Btn>
            <Btn variant="outline" onClick={() => setFav(!fav)}><Icon.Heart size={15} filled={fav} c={fav ? '#DC2626' : '#344054'} /></Btn>
          </div>
        </div>
        <div className="flex gap-1 border-b border-[#E4E7EC] mb-6">
          {tabs.map(t => (
            <button key={t} onClick={() => setTab(t)} className={`px-4 py-3 text-[13px] font-bold border-b-2 -mb-px ${tab === t ? 'border-[#2563EB] text-[#0B1F3A]' : 'border-transparent text-[#667085]'}`}>{t}</button>
          ))}
        </div>
        <div className="pb-14">
          {tab === 'Overview' && (
            <div className="grid grid-cols-[1fr_280px] gap-8">
              <div>
                <p className="text-[14px] leading-relaxed text-[#344054]">{f.description}</p>
                <div className="grid grid-cols-4 gap-4 mt-6">
                  {[[f.completed.toLocaleString(), 'shipments completed'], [f.onTime + '%', 'on-time'], [f.responseTime, 'avg response'], [f.rating, 'rating']].map(([v, l]) => (
                    <div key={l}><div className="text-[20px] font-extrabold text-[#0B1F3A] tabnum">{v}</div><div className="text-[12px] text-[#667085]">{l}</div></div>
                  ))}
                </div>
              </div>
              <Card hover={false} className="p-4 h-fit">
                <div className="text-[12px] font-bold text-[#667085] mb-2">CERTIFICATIONS</div>
                <div className="flex flex-wrap gap-1.5">{f.certifications.map(c => <span key={c} className="text-[11px] font-semibold bg-[#F7F8FA] px-2 py-1 rounded-md">{c}</span>)}</div>
              </Card>
            </div>
          )}
          {tab === 'Services' && (
            <div className="grid grid-cols-3 gap-4">
              {f.services.map(s => <Card key={s} className="p-4 text-[14px] font-semibold text-[#101828] flex items-center gap-2"><ModeIcon mode={s} size={18}/>{s}</Card>)}
            </div>
          )}
          {tab === 'Routes' && (
            <ul className="flex flex-col gap-2">
              {f.lanes.map(l => <li key={l} className="text-[14px] text-[#344054] border-b border-[#F1F3F6] py-2.5">{f.city} → {l}</li>)}
            </ul>
          )}
          {tab === 'Rates' && (
            <div className="text-[14px] text-[#667085]">Live rate cards from {f.name} are only visible after requesting a quote or opening an RFQ — keeps quoting on-platform.</div>
          )}
          {tab === 'Reviews' && (
            <div className="flex flex-col gap-3">
              {[['Nordic Safety AB', 'On-time and easy to work with on Japan air freight.'], ['Berlin Trade GmbH', 'Responsive and clear on documentation requirements.']].map(([n, t]) => (
                <Card key={n} hover={false} className="p-4"><div className="flex items-center gap-1 mb-1"><Icon.Star size={13}/><Icon.Star size={13}/><Icon.Star size={13}/><Icon.Star size={13}/><Icon.Star size={13}/></div><div className="text-[13px] text-[#344054]">{t}</div><div className="text-[12px] text-[#98A2B3] mt-1">{n}</div></Card>
              ))}
            </div>
          )}
          {tab === 'Company Info' && (
            <div className="grid grid-cols-2 gap-4 text-[14px]">
              <div><span className="text-[#667085]">Specialties: </span><span className="font-semibold">{f.specialties.join(', ')}</span></div>
              <div><span className="text-[#667085]">Founded: </span><span className="font-semibold">{f.founded}</span></div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function RoutesPage() {
  return (
    <div className="max-w-[1360px] mx-auto px-8 py-12">
      <SectionTitle sub="Search freight lanes for indicative rates, transit times and active forwarders.">Routes</SectionTitle>
      <div className="grid grid-cols-3 gap-5">
        {ROUTES.map(r => (
          <Card key={r.slug} className="overflow-hidden flex flex-col">
            <Link to={`/routes/${r.slug}`} className="h-32 block relative">
              <img src={r.cover} className="w-full h-full object-cover" alt={r.destination} />
              <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"></div>
              <span className="absolute bottom-2 left-3 text-white text-[16px] font-bold">{r.origin} → {r.destination}</span>
            </Link>
            <div className="p-5 pt-4 flex flex-col gap-2.5 flex-1">
              <div className="flex gap-1.5 flex-wrap">{r.modes.map(m => <span key={m} className="text-[11px] font-semibold bg-[#F7F8FA] px-2 py-0.5 rounded-full flex items-center gap-1"><ModeIcon mode={m} size={12}/>{m}</span>)}</div>
              <div className="text-[13px] text-[#667085]">From <span className="font-bold text-[#101828] tabnum">{r.rateFrom}</span> · {r.transit}</div>
              <div className="text-[12px] text-[#98A2B3]">{r.activeForwarders} active forwarders</div>
              <Btn to="/quote" size="sm" className="mt-auto w-full">Get Quote</Btn>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function RouteDetailPage() {
  const { slug } = useParams();
  const r = ROUTES.find(x => x.slug === slug) || ROUTES[0];
  const cover = r.cover;
  const topForwarders = FORWARDERS.filter(f => r.destCountry && (f.lanes.join(' ').toLowerCase().includes(r.destination.toLowerCase()) || f.lanes.some(l => r.destCountry.toLowerCase().includes(l.toLowerCase()) || l.toLowerCase().includes(r.destCountry.toLowerCase())))).slice(0, 3);
  const shown = topForwarders.length ? topForwarders : FORWARDERS.slice(0, 3);
  return (
    <div>
      <div className="h-[200px] relative">
        <img src={cover} className="w-full h-full object-cover" alt={r.destination} />
        <div className="absolute inset-0 bg-[#0B1F3A]/70 flex items-center">
          <div className="max-w-[1100px] mx-auto px-8 w-full">
            <h1 className="text-[30px] font-extrabold text-white m-0">{r.origin} to {r.destination} Freight Shipping</h1>
          </div>
        </div>
      </div>
      <div className="max-w-[1100px] mx-auto px-8 py-10 grid grid-cols-[1fr_300px] gap-8">
        <div className="flex flex-col gap-6">
          <Card hover={false} className="p-6">
            <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-3">MARKET SNAPSHOT</div>
            {r.market.map(m => (
              <div key={m.mode} className="flex justify-between py-2.5 border-b border-[#F1F3F6] text-[14px]"><span className="flex items-center gap-2 font-semibold"><ModeIcon mode={m.mode} size={16}/>{m.mode}</span><span className="tabnum">{m.range}</span><span className="text-[#667085]">{m.transit}</span></div>
            ))}
          </Card>
          <Card hover={false} className="p-6">
            <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-3">TOP FREIGHT FORWARDERS</div>
            <div className="flex flex-col gap-3">{shown.map(f => <ForwarderCard key={f.slug} f={f} />)}</div>
          </Card>
          <Card hover={false} className="p-6">
            <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-3">CUSTOMS NOTES</div>
            <p className="text-[13px] text-[#344054] leading-relaxed m-0">{r.notes}</p>
          </Card>
          <Card hover={false} className="p-6">
            <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-3">COMMON CARGO</div>
            <div className="flex gap-2 flex-wrap">{r.cargo.map(c => <span key={c} className="text-[12px] font-semibold bg-[#F7F8FA] px-2.5 py-1 rounded-full">{c}</span>)}</div>
          </Card>
        </div>
        <div className="flex flex-col gap-3 sticky top-24 h-fit">
          <Btn to="/quote" size="lg" className="w-full">Get Live Quote</Btn>
          <Btn to="/rfq/new" variant="outline" className="w-full">Post RFQ</Btn>
          <Btn to="/forwarders" variant="outline" className="w-full">Find Forwarders</Btn>
        </div>
      </div>
    </div>
  );
}

const SHIPMENT_TABS = ['All', 'Booked', 'In Transit', 'Delivered', 'Exception'];

function ShipmentsPage() {
  const [tab, setTab] = useState('All');
  const list = tab === 'All' ? SHIPMENTS : SHIPMENTS.filter(s => s.status === tab);
  return (
    <div className="max-w-[1360px] mx-auto px-8 py-12">
      <SectionTitle>My Shipments</SectionTitle>
      <div className="flex gap-1 bg-[#F7F8FA] rounded-lg p-1 mb-6 w-fit">
        {SHIPMENT_TABS.map(t => (
          <button key={t} onClick={() => setTab(t)} className={`px-4 py-2 rounded-md text-[13px] font-bold ${tab === t ? 'bg-white shadow text-[#0B1F3A]' : 'text-[#667085]'}`}>{t}</button>
        ))}
      </div>
      <Card hover={false} className="overflow-hidden">
        <div className="grid grid-cols-7 px-5 py-3 bg-[#F7F8FA] border-b border-[#E4E7EC] text-[11px] font-bold text-[#667085]">
          <span>SHIPMENT ID</span><span>ROUTE</span><span>SUPPLIER</span><span>MODE</span><span>STATUS</span><span>ETA</span><span>TOTAL</span>
        </div>
        {list.map((s, i) => (
          <Link to={`/shipments/${s.id}`} key={s.id} className={`grid grid-cols-7 px-5 py-4 items-center text-[13px] hover:bg-[#F7F8FA] ${i < list.length - 1 ? 'border-b border-[#F1F3F6]' : ''}`}>
            <span className="font-bold text-[#101828] tabnum">{s.id}</span>
            <span className="text-[#344054]">{s.route}</span>
            <span className="text-[#344054]">{s.supplier}</span>
            <span className="text-[#344054]">{s.mode}</span>
            <span className={`text-[11px] font-bold px-2 py-0.5 rounded-full w-fit ${s.status === 'Delivered' ? 'bg-[#EFFBF1] text-[#16A34A]' : s.status === 'Exception' ? 'bg-[#FDECEC] text-[#DC2626]' : s.status === 'In Transit' ? 'bg-[#EEF4FF] text-[#2563EB]' : 'bg-[#FFF7E8] text-[#B45309]'}`}>{s.status}</span>
            <span className="text-[#344054] tabnum">{s.eta}</span>
            <span className="font-bold tabnum">${s.total}</span>
          </Link>
        ))}
      </Card>
    </div>
  );
}

function ShipmentDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const s = SHIPMENTS.find(x => x.id === id) || SHIPMENTS[0];
  return (
    <div className="max-w-[1000px] mx-auto px-8 py-12">
      <div className="mb-6">
        <div className="text-[13px] font-bold text-[#98A2B3] tabnum">{s.id}</div>
        <h1 className="text-[26px] font-extrabold text-[#0B1F3A] m-0">{s.route}</h1>
      </div>
      <Card hover={false} className="p-6 mb-6">
        <div className="text-[13px] font-bold text-[#667085] tracking-wide mb-5">STATUS TIMELINE</div>
        <div className="flex items-center">
          {TIMELINE_STEPS.map((step, i) => (
            <div key={step} className="flex-1 flex flex-col items-center relative">
              {i > 0 && <div className={`absolute h-0.5 top-3.5 right-1/2 w-full ${i <= s.timelineStep ? 'bg-[#2563EB]' : 'bg-[#E4E7EC]'}`}></div>}
              <div className={`w-7 h-7 rounded-full flex items-center justify-center text-[11px] font-bold z-10 ${i < s.timelineStep ? 'bg-[#2563EB] text-white' : i === s.timelineStep ? 'bg-[#2563EB] text-white ring-4 ring-[#EEF4FF]' : 'bg-white border-2 border-[#E4E7EC] text-[#98A2B3]'}`}>{i < s.timelineStep ? <Icon.Check size={13} c="white"/> : i + 1}</div>
              <div className="text-[10px] text-[#667085] mt-2 text-center max-w-[70px]">{step}</div>
            </div>
          ))}
        </div>
      </Card>
      <Card hover={false} className="p-5 mb-6 bg-[#F7F8FA] border-[#E4E7EC] flex items-start gap-3">
        <Icon.Sparkle size={18} c="#2563EB" />
        <div className="text-[14px] text-[#344054]">Shipment {s.status === 'In Transit' ? 'departed on schedule. Current ETA is ' + s.eta + '. No action is required.' : s.status === 'Delivered' ? 'was delivered successfully on ' + s.eta + '.' : s.status === 'Exception' ? 'requires additional customs documentation before it can proceed.' : 'is booked and awaiting pickup.'}</div>
      </Card>
      <div className="grid grid-cols-2 gap-4 mb-6">
        <Card hover={false} className="p-5"><div className="text-[12px] font-bold text-[#667085] mb-2">SUPPLIER</div><Link to={`/forwarders/${s.supplierSlug}`} className="text-[14px] font-semibold text-[#2563EB]">{s.supplier}</Link></Card>
        <Card hover={false} className="p-5"><div className="text-[12px] font-bold text-[#667085] mb-2">CHARGES</div><div className="text-[14px] font-bold tabnum">${s.total}</div></Card>
        <Card hover={false} className="p-5"><div className="text-[12px] font-bold text-[#667085] mb-2">CARGO</div><div className="text-[14px]">{s.cargo}</div></Card>
        <Card hover={false} className="p-5"><div className="text-[12px] font-bold text-[#667085] mb-2">ETD / ETA</div><div className="text-[14px] tabnum">{s.etd} → {s.eta}</div></Card>
      </div>
      <div className="flex gap-3">
        {s.status === 'Delivered' && <Btn onClick={() => navigate('/quote')}>Ship This Again</Btn>}
        <Btn variant="outline">Documents</Btn>
        <Btn variant="outline">Messages</Btn>
        <Btn variant="ghost">Claim / Support</Btn>
      </div>
    </div>
  );
}

function AIAssistantPage() {
  const [messages, setMessages] = useState([
    { role: 'user', text: 'Should I ship 2.8 CBM from Ningbo to Sweden by air or sea?' },
    { role: 'ai', text: 'LCL is likely more economical if your delivery window is over 20 days. Current market range is approximately $55–$72/CBM before destination charges. I found 12 matching suppliers.', reason: 'LCL avoids the per-kg air premium; at 2.8 CBM the break-even versus air freight is typically a 15–18 day window.' },
  ]);
  const [input, setInput] = useState('');
  const endRef = useRef(null);
  useEffect(() => { endRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]);
  function send() {
    if (!input.trim()) return;
    const reply = AI_CANNED_REPLIES[messages.length % AI_CANNED_REPLIES.length];
    setMessages(m => [...m, { role: 'user', text: input }, { role: 'ai', text: reply }]);
    setInput('');
  }
  return (
    <div className="flex h-[calc(100vh-76px)]">
      <div className="w-[240px] bg-[#F7F8FA] border-r border-[#E4E7EC] p-4 flex flex-col gap-1 shrink-0">
        <Btn className="w-full mb-3">+ New Chat</Btn>
        {[['Freight Quote', '/quote'], ['Compare Quotes', '/quote/results'], ['Find Forwarders', '/forwarders'], ['Shipping Advice', '/ai'], ['Customs Questions', '/ai'], ['My Shipments', '/shipments']].map(([l, href]) => (
          <Link key={l} to={href} className="px-3 py-2 rounded-lg text-[13px] text-[#344054] hover:bg-white hover:shadow-sm">{l}</Link>
        ))}
      </div>
      <div className="flex-1 flex flex-col">
        <div className="flex-1 overflow-y-auto p-8 flex flex-col gap-4 max-w-[760px] mx-auto w-full">
          {messages.map((m, i) => (
            <div key={i} className={`max-w-[80%] px-4 py-3 rounded-2xl text-[14px] leading-relaxed ${m.role === 'user' ? 'self-end bg-[#0B1F3A] text-white rounded-br-md' : 'self-start bg-[#F7F8FA] text-[#101828] rounded-bl-md'}`}>
              {m.text}
              {m.reason && <div className="mt-2.5"><AIReasonChip label="Why this?" reason={m.reason} /></div>}
            </div>
          ))}
          <div ref={endRef}></div>
        </div>
        <div className="border-t border-[#E4E7EC] p-4">
          <div className="max-w-[760px] mx-auto flex items-center gap-2">
            <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder="Ask about rates, forwarders, or your shipments…" className="flex-1 border border-[#E4E7EC] rounded-lg px-4 py-3 text-[14px] outline-none focus:border-[#2563EB]" />
            <Btn onClick={send}><Icon.Send size={15} c="white"/></Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

function AuthPage() {
  const navigate = useNavigate();
  const [mode, setMode] = useState('signin');
  const [accountType, setAccountType] = useState('shipper');
  function submit(e) {
    e.preventDefault();
    if (mode === 'signup' && accountType === 'forwarder') navigate('/supplier/onboarding');
    else navigate('/');
  }
  return (
    <div className="max-w-[420px] mx-auto px-8 py-16">
      <div className="flex gap-1 bg-[#F7F8FA] rounded-lg p-1 mb-8">
        <button onClick={() => setMode('signin')} className={`flex-1 py-2.5 rounded-md text-[13px] font-bold ${mode === 'signin' ? 'bg-white shadow text-[#0B1F3A]' : 'text-[#667085]'}`}>Sign In</button>
        <button onClick={() => setMode('signup')} className={`flex-1 py-2.5 rounded-md text-[13px] font-bold ${mode === 'signup' ? 'bg-white shadow text-[#0B1F3A]' : 'text-[#667085]'}`}>Sign Up</button>
      </div>
      <form onSubmit={submit} className="flex flex-col gap-3.5">
        {mode === 'signup' && (
          <div className="flex gap-2 mb-1">
            {[['shipper', 'Shipper / Buyer'], ['forwarder', 'Freight Forwarder']].map(([v, l]) => (
              <button type="button" key={v} onClick={() => setAccountType(v)} className={`flex-1 border rounded-lg py-2.5 text-[12px] font-bold ${accountType === v ? 'border-[#2563EB] bg-[#EEF4FF] text-[#2563EB]' : 'border-[#E4E7EC] text-[#667085]'}`}>{l}</button>
            ))}
          </div>
        )}
        {mode === 'signup' && <input required placeholder="Full name" className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px] outline-none focus:border-[#2563EB]" />}
        {mode === 'signup' && <input required placeholder="Company" className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px] outline-none focus:border-[#2563EB]" />}
        <input required type="email" placeholder="Email" className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px] outline-none focus:border-[#2563EB]" />
        <input required type="password" placeholder="Password" className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px] outline-none focus:border-[#2563EB]" />
        <Btn type="submit" size="lg" className="mt-1">{mode === 'signin' ? 'Sign In' : accountType === 'forwarder' ? 'Continue to Supplier Onboarding' : 'Create Account'}</Btn>
        <div className="text-center text-[12px] text-[#98A2B3]">or continue with Google / Company account</div>
      </form>
    </div>
  );
}

function PricingPage() {
  return (
    <div className="max-w-[1200px] mx-auto px-8 py-16">
      <div className="text-center mb-12">
        <h1 className="text-[34px] font-extrabold text-[#0B1F3A] m-0 mb-3">Simple pricing for freight forwarders</h1>
        <p className="text-[15px] text-[#667085] m-0">Shippers always search, quote and post RFQs for free. Forwarders choose the plan that fits their volume.</p>
      </div>
      <div className="grid grid-cols-3 gap-6">
        {PRICING_PLANS.map(p => (
          <Card key={p.name} hover={false} className={`p-7 flex flex-col ${p.highlight ? 'ring-2 ring-[#2563EB] relative' : ''}`}>
            {p.highlight && <span className="absolute -top-3 left-7 bg-[#2563EB] text-white text-[11px] font-bold px-3 py-1 rounded-full">Most Popular</span>}
            <div className="text-[16px] font-bold text-[#101828]">{p.name}</div>
            <div className="text-[12px] text-[#667085] mb-4">{p.audience}</div>
            <div className="flex items-baseline gap-1 mb-6"><span className="text-[34px] font-extrabold text-[#0B1F3A] tabnum">{p.price}</span><span className="text-[13px] text-[#98A2B3]">{p.period}</span></div>
            <div className="flex flex-col gap-2.5 mb-6 flex-1">
              {p.features.map(f => <div key={f} className="flex items-start gap-2 text-[13px] text-[#344054]"><Icon.Check size={15} c="#16A34A"/><span>{f}</span></div>)}
            </div>
            <Btn to="/login" variant={p.highlight ? 'primary' : 'outline'} className="w-full">{p.cta}</Btn>
          </Card>
        ))}
      </div>
    </div>
  );
}

function AboutPage() {
  return (
    <div>
      <div className="h-[240px] relative">
        <img src="assets/warehouse.jpg" className="w-full h-full object-cover" alt="Modern logistics warehouse" />
        <div className="absolute inset-0 bg-[#0B1F3A]/75 flex items-center">
          <div className="max-w-[900px] mx-auto px-8 text-center">
            <h1 className="text-[32px] font-extrabold text-white m-0">Making freight procurement as easy as online shopping</h1>
          </div>
        </div>
      </div>
      <div className="max-w-[900px] mx-auto px-8 py-14">
        <p className="text-[15px] leading-relaxed text-[#344054]">FFwarder started with a simple observation: shippers were still comparing freight rates over email threads and PDF quotes, while every other B2B purchase had moved to instant, comparable, on-platform pricing. We built FFwarder to bring the AI Quote + RFQ marketplace model already common in other industries to freight forwarding — without losing the relationship and trust that moving physical cargo requires.</p>
        <div className="grid grid-cols-4 gap-6 my-10 text-center">
          {[['20+', 'Verified forwarders'], ['500+', 'Active lanes'], ['1,200+', 'Shipments matched'], ['96%', 'Average on-time rate']].map(([v, l]) => (
            <div key={l}><div className="text-[26px] font-extrabold text-[#0B1F3A] tabnum">{v}</div><div className="text-[12px] text-[#667085]">{l}</div></div>
          ))}
        </div>
        <h2 className="text-[20px] font-bold text-[#0B1F3A]">Our approach</h2>
        <p className="text-[15px] leading-relaxed text-[#344054]">We match shippers to forwarders two ways at once — instant rates from suppliers’ own rate cards, and RFQ bidding when a shipment needs more competitive coverage. AI sits underneath both flows: parsing shipment requirements, matching suppliers by route and cargo type, and explaining every recommendation it makes.</p>
      </div>
    </div>
  );
}

function TrustSafetyPage() {
  return (
    <div className="max-w-[900px] mx-auto px-8 py-16">
      <SectionTitle sub="How we keep a marketplace moving real freight money accountable on both sides.">Trust &amp; Safety</SectionTitle>
      <div className="flex flex-col gap-5">
        <Card hover={false} className="p-6">
          <div className="text-[15px] font-bold text-[#101828] mb-2">Three verification tiers</div>
          <div className="grid grid-cols-3 gap-4 text-[13px]">
            <div><VerifiedBadge tier="pending"/><p className="mt-2 text-[#667085]">New signups. Can browse and quote, but flagged to buyers until reviewed.</p></div>
            <div><VerifiedBadge tier="verified"/><p className="mt-2 text-[#667085]">Business license and FIATA/NVOCC/IATA credentials checked by our team.</p></div>
            <div><span className="inline-flex items-center gap-1 bg-[#EEF4FF] text-[#2563EB] text-[11px] font-bold px-2 py-0.5 rounded-full"><Icon.Star size={11} c="#2563EB"/> Top Rated</span><p className="mt-2 text-[#667085]">Verified + a sustained 90-day on-time and response record.</p></div>
          </div>
        </Card>
        <Card hover={false} className="p-6">
          <div className="text-[15px] font-bold text-[#101828] mb-2">Disputes &amp; claims</div>
          <p className="text-[13px] text-[#667085] leading-relaxed">Every shipment has a claim thread visible to both the customer and the supplier — delay, damage, customs hold, or documentation issues are never resolved in a black box. Status moves through Submitted → Under Review → Resolved, with an Escalated path if either side disagrees with the outcome.</p>
        </Card>
        <Card hover={false} className="p-6 border-[#F5D9A8] bg-[#FFFBF2]">
          <div className="text-[15px] font-bold text-[#B45309] mb-2">Rate integrity</div>
          <p className="text-[13px] text-[#8A5A0A] leading-relaxed">Reference rates suppliers upload feed our AI matching and instant-quote systems directly. Submitting fabricated, bait-and-switch, or manipulated rates to inflate ranking is grounds for immediate and permanent account suspension.</p>
        </Card>
      </div>
    </div>
  );
}

function NewsPage() {
  return (
    <div className="max-w-[1200px] mx-auto px-8 py-14">
      <SectionTitle sub="Rate trends, capacity alerts, and regulatory changes from across the FFwarder network.">Freight market news</SectionTitle>
      <div className="grid grid-cols-3 gap-5">
        {NEWS_ARTICLES.map(a => <NewsCard key={a.slug} a={a} />)}
      </div>
    </div>
  );
}

function NewsArticlePage() {
  const { slug } = useParams();
  const a = NEWS_ARTICLES.find(x => x.slug === slug) || NEWS_ARTICLES[0];
  return (
    <div>
      <div className="h-[280px] relative">
        <img src={a.img} className="w-full h-full object-cover" alt={a.title} />
        <div className="absolute inset-0 bg-gradient-to-t from-[#0B1F3A]/90 to-transparent"></div>
        <div className="absolute bottom-0 left-0 right-0 max-w-[780px] mx-auto px-8 pb-8">
          <span className="text-[11px] font-bold text-[#93C5FD] uppercase tracking-wide">{a.tag} · {a.date}</span>
          <h1 className="text-[28px] font-extrabold text-white m-0 mt-1">{a.title}</h1>
        </div>
      </div>
      <div className="max-w-[780px] mx-auto px-8 py-12">
        <p className="text-[16px] leading-relaxed text-[#344054]">{a.body}</p>
        <Btn to="/news" variant="outline" className="mt-6">← All Market News</Btn>
      </div>
    </div>
  );
}

function ContactPage() {
  const [sent, setSent] = useState(false);
  return (
    <div className="max-w-[560px] mx-auto px-8 py-16">
      <SectionTitle sub="Questions about a shipment, a partnership, or the platform itself.">Contact FFwarder</SectionTitle>
      {sent ? (
        <Card hover={false} className="p-8 text-center"><div className="text-[15px] font-bold text-[#101828]">Message sent</div><div className="text-[13px] text-[#667085] mt-1">We typically respond within one business day.</div></Card>
      ) : (
        <form onSubmit={e => { e.preventDefault(); setSent(true); }} className="flex flex-col gap-3.5">
          <input required placeholder="Name" className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px] outline-none focus:border-[#2563EB]" />
          <input required type="email" placeholder="Email" className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px] outline-none focus:border-[#2563EB]" />
          <textarea required rows={5} placeholder="How can we help?" className="border border-[#E4E7EC] rounded-lg px-3.5 py-2.5 text-[14px] outline-none focus:border-[#2563EB] resize-none"></textarea>
          <Btn type="submit" size="lg">Send Message</Btn>
        </form>
      )}
    </div>
  );
}
function KPICard({ label, value }) {
  return <Card hover={false} className="p-4"><div className="text-[12px] text-[#667085] mb-1">{label}</div><div className="text-[22px] font-extrabold text-[#0B1F3A] tabnum">{value}</div></Card>;
}

function SupplierDashboardPage() {
  const navigate = useNavigate();
  return (
    <SupplierLayout active="工作台">
      <div className="grid grid-cols-6 gap-4 mb-8">
        <KPICard label="今日新询盘" value="18" />
        <KPICard label="待报价" value="7" />
        <KPICard label="本月报价" value="126" />
        <KPICard label="本月成交" value="23" />
        <KPICard label="报价转化率" value="18.3%" />
        <KPICard label="平均响应时间" value="16分钟" />
      </div>

      <div className="text-[15px] font-bold text-[#101828] mb-3">推荐商机</div>
      <div className="grid grid-cols-2 gap-4 mb-8">
        <Card hover={false} className="p-5">
          <div className="flex items-center justify-between mb-2">
            <span className="text-[16px] font-bold text-[#101828]">宁波 → 东京</span>
            <span className="text-[11px] font-bold bg-[#EFFBF1] text-[#16A34A] px-2 py-0.5 rounded-full">匹配度 97%</span>
          </div>
          <div className="text-[13px] text-[#667085] mb-1">空运 · 280kg</div>
          <div className="text-[13px] text-[#B45309] mb-4">客户要求 7 天以内 · 剩余报价时间 5 小时</div>
          <div className="flex gap-2">
            <Btn onClick={() => navigate('/supplier/rfq/1')} size="sm">立即报价</Btn>
            <Btn variant="outline" size="sm" onClick={() => navigate('/supplier/rfq/1')}>查看详情</Btn>
          </div>
        </Card>
        <Card hover={false} className="p-5">
          <div className="flex items-center justify-between mb-2">
            <span className="text-[16px] font-bold text-[#101828]">深圳 → 洛杉矶</span>
            <span className="text-[11px] font-bold bg-[#EEF4FF] text-[#2563EB] px-2 py-0.5 rounded-full">匹配度 93%</span>
          </div>
          <div className="text-[13px] text-[#667085] mb-1">电池货 · 620kg</div>
          <div className="text-[13px] text-[#667085] mb-4">需要 UN38.3 文件</div>
          <div className="flex gap-2">
            <Btn onClick={() => navigate('/supplier/rfq/1')} size="sm">立即报价</Btn>
            <Btn variant="outline" size="sm" onClick={() => navigate('/supplier/rfq/1')}>查看详情</Btn>
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-2 gap-6">
        <Card hover={false} className="p-5">
          <div className="text-[14px] font-bold text-[#101828] mb-3">最近报价</div>
          {[['宁波 → 东京', '已提交'], ['上海 → 汉堡', '客户已读'], ['深圳 → 法兰克福', '入围'], ['宁波 → 奥斯陆', '已成交']].map(([r, s], i) => (
            <div key={i} className="flex items-center justify-between py-2.5 border-b border-[#F1F3F6] last:border-0 text-[13px]">
              <span className="text-[#344054]">{r}</span>
              <span className={`text-[11px] font-bold px-2 py-0.5 rounded-full ${s === '已成交' ? 'bg-[#EFFBF1] text-[#16A34A]' : s === '入围' ? 'bg-[#EEF4FF] text-[#2563EB]' : 'bg-[#FFF7E8] text-[#B45309]'}`}>{s}</span>
            </div>
          ))}
        </Card>
        <Card hover={false} className="p-5">
          <div className="text-[14px] font-bold text-[#101828] mb-3">运价健康度</div>
          <div className="grid grid-cols-2 gap-4">
            <div><div className="text-[20px] font-extrabold text-[#16A34A] tabnum">326</div><div className="text-[12px] text-[#667085]">有效运价</div></div>
            <div><div className="text-[20px] font-extrabold text-[#F59E0B] tabnum">48</div><div className="text-[12px] text-[#667085]">7天内过期</div></div>
            <div><div className="text-[20px] font-extrabold text-[#DC2626] tabnum">31</div><div className="text-[12px] text-[#667085]">已过期</div></div>
            <div><div className="text-[20px] font-extrabold text-[#0B1F3A] tabnum">65</div><div className="text-[12px] text-[#667085]">建议更新</div></div>
          </div>
        </Card>
      </div>
    </SupplierLayout>
  );
}

function SupplierRFQSubmitPage() {
  const [submitted, setSubmitted] = useState(false);
  const [note, setNote] = useState('');
  return (
    <SupplierLayout active="推荐询盘">
      <div className="grid grid-cols-[1fr_380px] gap-6">
        <Card hover={false} className="p-6">
          <div className="text-[13px] font-bold text-[#667085] mb-4">完整客户运输需求</div>
          <div className="flex flex-col gap-2.5 text-[14px]">
            <div className="flex justify-between"><span className="text-[#667085]">路线</span><span className="font-bold">宁波 → 东京</span></div>
            <div className="flex justify-between"><span className="text-[#667085]">运输方式</span><span className="font-bold">空运</span></div>
            <div className="flex justify-between"><span className="text-[#667085]">重量</span><span className="font-bold">280 kg</span></div>
            <div className="flex justify-between"><span className="text-[#667085]">货物</span><span className="font-bold">反光背心</span></div>
            <div className="flex justify-between"><span className="text-[#667085]">Ready Date</span><span className="font-bold">Oct 8</span></div>
            <div className="flex justify-between"><span className="text-[#667085]">要求时效</span><span className="font-bold">7 天内</span></div>
          </div>
        </Card>

        {!submitted ? (
          <Card hover={false} className="p-6">
            <div className="text-[13px] font-bold text-[#667085] mb-4">报价表单</div>
            <div className="grid grid-cols-2 gap-3 mb-3">
              {['基础运费', '附加费', '提货费', '报关费', '目的港费用', '派送费'].map((l, i) => (
                <div key={l}>
                  <div className="text-[11px] font-semibold text-[#667085] mb-1">{l}</div>
                  <input defaultValue={[220, 15, 20, 25, 18, 22][i]} className="w-full border border-[#E4E7EC] rounded-lg px-2.5 py-2 text-[13px] tabnum" />
                </div>
              ))}
            </div>
            <div className="text-[11px] font-semibold text-[#667085] mb-1">时效 / 有效期</div>
            <div className="grid grid-cols-2 gap-3 mb-3">
              <input defaultValue="4–6 天" className="border border-[#E4E7EC] rounded-lg px-2.5 py-2 text-[13px]" />
              <input defaultValue="Oct 12" className="border border-[#E4E7EC] rounded-lg px-2.5 py-2 text-[13px]" />
            </div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-[11px] font-semibold text-[#667085]">备注</span>
              <button type="button" onClick={() => setNote('含提货、报关报检一站式服务，日本目的港担保代理处理。')} className="text-[11px] font-bold text-[#2563EB]">AI 帮我生成报价说明</button>
            </div>
            <textarea value={note} onChange={e => setNote(e.target.value)} rows={3} className="w-full border border-[#E4E7EC] rounded-lg px-2.5 py-2 text-[13px] resize-none mb-4" />
            <Btn onClick={() => setSubmitted(true)} size="lg" className="w-full">提交报价</Btn>
          </Card>
        ) : (
          <Card hover={false} className="p-6">
            <div className="text-[15px] font-bold text-[#101828] mb-4">报价已提交</div>
            <div className="flex flex-col gap-3 text-[13px]">
              <div className="flex justify-between"><span className="text-[#667085]">客户是否已读</span><span className="font-bold text-[#B45309]">尚未读取</span></div>
              <div className="flex justify-between"><span className="text-[#667085]">当前排名区间</span><span className="font-bold">前 3 名</span></div>
              <div className="flex justify-between"><span className="text-[#667085]">是否入围</span><span className="font-bold text-[#16A34A]">待客户选择</span></div>
            </div>
            <div className="mt-4 bg-[#F7F8FA] rounded-lg px-3.5 py-3 text-[12px] text-[#667085]">为保护价格竞争，平台不展示其他供应商的绝对报价。</div>
          </Card>
        )}
      </div>
    </SupplierLayout>
  );
}

function CheckGrid({ options, selected, onToggle, cols }) {
  return (
    <div className={`grid gap-2.5`} style={{ gridTemplateColumns: `repeat(${cols || 3}, minmax(0,1fr))` }}>
      {options.map(o => (
        <label key={o} className={`flex items-center gap-2 text-[13px] border rounded-lg px-3 py-2.5 cursor-pointer ${selected.includes(o) ? 'border-[#2563EB] bg-[#EEF4FF] text-[#2563EB] font-semibold' : 'border-[#E4E7EC] text-[#344054]'}`}>
          <input type="checkbox" className="accent-[#2563EB]" checked={selected.includes(o)} onChange={() => onToggle(o)} />
          {o}
        </label>
      ))}
    </div>
  );
}

function UploadSlot({ label, hint }) {
  const [uploaded, setUploaded] = useState(false);
  return (
    <div>
      <div className="text-[12px] font-semibold text-[#667085] mb-1.5">{label}</div>
      <label className="flex items-center gap-3 border border-dashed border-[#E4E7EC] rounded-lg px-4 py-3.5 cursor-pointer hover:border-[#2563EB]">
        <input type="file" className="hidden" onChange={() => setUploaded(true)} />
        <div className="w-8 h-8 rounded-lg bg-[#EEF4FF] flex items-center justify-center shrink-0">
          <Icon.ArrowRight size={14} c="#2563EB" />
        </div>
        <div className="flex-1">
          <div className="text-[13px] font-semibold text-[#101828]">{uploaded ? '已上传：文件.pdf' : '点击上传或拖拽文件到此处'}</div>
          {hint && <div className="text-[11px] text-[#98A2B3]">{hint}</div>}
        </div>
        {uploaded && <Icon.Check size={16} c="#16A34A" />}
      </label>
    </div>
  );
}

const ONBOARD_STEPS = ['公司基本信息', '资质认证', '服务能力', '优势航线', '公司介绍与联系人', '完成'];

function SupplierOnboardingPage() {
  const navigate = useNavigate();
  const [step, setStep] = useState(0);
  const [services, setServices] = useState(['空运', '海运 LCL']);
  const [specialties, setSpecialties] = useState(['Amazon FBA']);
  const [certs, setCerts] = useState(['FIATA']);
  const [origins, setOrigins] = useState(['宁波']);
  const [dests, setDests] = useState(['日本/韩国']);
  const toggle = (setter) => (val) => setter(list => list.includes(val) ? list.filter(x => x !== val) : [...list, val]);

  return (
    <div className="min-h-screen bg-[#F7F8FA] py-10 px-8">
      <div className="max-w-[760px] mx-auto">
        <div className="text-center mb-8">
          <div className="text-[20px] font-extrabold text-[#0B1F3A]">货代入驻申请</div>
          <div className="text-[13px] text-[#667085] mt-1">资料越完整，AI 智能匹配系统推送的询盘越精准、越充足</div>
        </div>
        <div className="flex items-center gap-1.5 mb-8">
          {ONBOARD_STEPS.map((s, i) => (
            <div key={s} className="flex items-center gap-1.5 flex-1">
              <div className={`w-7 h-7 rounded-full flex items-center justify-center text-[11px] font-bold shrink-0 ${i <= step ? 'bg-[#2563EB] text-white' : 'bg-white border border-[#E4E7EC] text-[#98A2B3]'}`}>{i + 1}</div>
              {i < ONBOARD_STEPS.length - 1 && <div className={`flex-1 h-0.5 ${i < step ? 'bg-[#2563EB]' : 'bg-[#E4E7EC]'}`}></div>}
            </div>
          ))}
        </div>
        <Card hover={false} className="p-7 min-h-[380px] flex flex-col">
          <div className="text-[17px] font-bold text-[#101828] mb-5">{ONBOARD_STEPS[step]}</div>
          <div className="flex-1 flex flex-col gap-4">
            {step === 0 && (
              <>
                <div className="grid grid-cols-2 gap-3.5">
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">公司名称</div><input defaultValue="宁波蓝海国际货运代理有限公司" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px]" /></div>
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">统一社会信用代码</div><input defaultValue="91330211MA2XXXXXX" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px] tabnum" /></div>
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">成立年份</div><input defaultValue="2011" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px] tabnum" /></div>
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">员工规模</div>
                    <select className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px] bg-white">
                      {['1–10人', '11–50人', '51–200人', '200人以上'].map(o => <option key={o}>{o}</option>)}
                    </select>
                  </div>
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">总部城市</div><input defaultValue="浙江省宁波市" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px]" /></div>
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">官网（选填）</div><input placeholder="https://" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px]" /></div>
                </div>
              </>
            )}
            {step === 1 && (
              <>
                <UploadSlot label="营业执照（必传）" hint="支持 JPG/PNG/PDF，小于 10MB" />
                <div className="text-[12px] font-semibold text-[#667085] mt-2 mb-1.5">拥有的资质认证（多选）</div>
                <CheckGrid options={SUPPLIER_CERTS} selected={certs} onToggle={toggle(setCerts)} cols={4} />
                {certs.length > 0 && <UploadSlot label={`上传资质证书（${certs.join('、')}）`} hint="可打包上传多个文件" />}
              </>
            )}
            {step === 2 && (
              <>
                <div className="text-[12px] font-semibold text-[#667085] mb-1.5">服务类型（多选）</div>
                <CheckGrid options={SUPPLIER_SERVICE_TYPES} selected={services} onToggle={toggle(setServices)} cols={4} />
                <div className="text-[12px] font-semibold text-[#667085] mt-3 mb-1.5">特殊货物能力（多选）</div>
                <CheckGrid options={SUPPLIER_SPECIALTIES} selected={specialties} onToggle={toggle(setSpecialties)} cols={3} />
              </>
            )}
            {step === 3 && (
              <>
                <div className="bg-[#EEF4FF] text-[#2563EB] text-[12px] rounded-lg px-3.5 py-2.5 flex items-center gap-2"><Icon.Sparkle size={14}/> 选择的优势起运港与目的地，将直接用于 AI 询盘匹配——覆盖越完整，推送机会越多</div>
                <div className="text-[12px] font-semibold text-[#667085] mt-2 mb-1.5">主要起运港（多选）</div>
                <CheckGrid options={SUPPLIER_ORIGIN_PORTS} selected={origins} onToggle={toggle(setOrigins)} cols={4} />
                <div className="text-[12px] font-semibold text-[#667085] mt-3 mb-1.5">主要目的地区域（多选）</div>
                <CheckGrid options={SUPPLIER_DEST_REGIONS} selected={dests} onToggle={toggle(setDests)} cols={4} />
                <div><div className="text-[12px] font-semibold text-[#667085] mt-3 mb-1.5">其他航线补充（选填）</div><input placeholder="例如：杭州→温哥华" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px]" /></div>
              </>
            )}
            {step === 4 && (
              <>
                <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">公司介绍与核心优势</div>
                  <textarea rows={4} defaultValue="专注日本、韩国及北欧航线空海运代理 10 年，自有日本目的港担保代理网络，支持一站式报关报检及清关服务。" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px] resize-none"></textarea>
                </div>
                <div className="grid grid-cols-2 gap-3.5">
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">联系人姓名</div><input placeholder="张经理" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px]" /></div>
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">职位</div><input placeholder="销售总监" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px]" /></div>
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">手机</div><input placeholder="+86 138 xxxx xxxx" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px] tabnum" /></div>
                  <div><div className="text-[12px] font-semibold text-[#667085] mb-1.5">邮箱</div><input placeholder="sales@example.com" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px]" /></div>
                </div>
              </>
            )}
            {step === 5 && (
              <div className="flex flex-col items-center text-center gap-3 py-10">
                <div className="w-14 h-14 rounded-full bg-[#EFFBF1] flex items-center justify-center"><Icon.Check size={26} c="#16A34A"/></div>
                <div className="text-[18px] font-bold text-[#101828]">资料已提交，人工审核中</div>
                <p className="text-[13px] text-[#667085] max-w-[440px] leading-relaxed">审核通常需要 1–2 个工作日。审核通过后您的资质弽窗会变为“已认证”，并开始根据本次填写的服务能力与优势航线接收 AI 匹配的询盘。</p>
                <Btn onClick={() => navigate('/supplier/dashboard')} size="lg" className="mt-2">进入供应商工作台</Btn>
              </div>
            )}
          </div>
          {step < 5 && (
            <div className="flex justify-between mt-6">
              <Btn variant="outline" onClick={() => setStep(s => Math.max(0, s - 1))} className={step === 0 ? 'invisible' : ''}>上一步</Btn>
              <Btn onClick={() => setStep(s => s + 1)}>{step === ONBOARD_STEPS.length - 2 ? '提交审核' : '下一步'}</Btn>
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}

function SupplierRatesPage() {
  const [imported, setImported] = useState(false);
  const rates = [
    ['宁波', '东京', '空运', '+100kg', 'CNY 12.5/kg', 'FSC 1.2', 'Oct 15', '有效'],
    ['上海', '汉堡', 'LCL', '/CBM', 'CNY 350', '—', 'Sep 30', '已过期'],
    ['深圳', '洛杉矶', '空运', '+45kg', 'CNY 22.8/kg', 'FSC 1.5', 'Oct 5', '待更新'],
  ];
  return (
    <SupplierLayout active="运价管理">
      <div className="bg-[#FDECEC] border border-[#F3B4B4] rounded-xl px-5 py-4 mb-6 flex gap-3">
        <div className="text-[#DC2626] shrink-0 mt-0.5"><Icon.Sparkle size={18} c="#DC2626"/></div>
        <div className="text-[13px] text-[#7A1F1F] leading-relaxed">
          <span className="font-bold">请上传真实参考运价。</span> 这些数据将作为平台 AI 智能报价与匹配系统的基础数据直接使用。若发现虚假报价、恶意刻意抬高/压低价格等行为，平台将永久封禁账号并保留追究相应责任的权利。建议每 7 天更新一次，超过 30 天未更新的运价会自动标记为“待更新”。
        </div>
      </div>

      <div className="flex gap-2 mb-6">
        <Btn size="sm" onClick={() => setImported(false)}>上传 Excel</Btn>
        <Btn variant="outline" size="sm">上传 PDF</Btn>
        <Btn variant="outline" size="sm">手工添加</Btn>
        <Btn variant="outline" size="sm">API 接入</Btn>
        <Btn variant="ghost" size="sm">下载模板</Btn>
      </div>

      {!imported ? (
        <Card hover={false} className="p-6 mb-6 border-dashed">
          <div className="text-[13px] font-bold text-[#667085] mb-3">AI 导入预览</div>
          <div className="flex items-center gap-3 mb-4">
            <div className="w-9 h-9 rounded-lg bg-[#EEF4FF] flex items-center justify-center"><Icon.Sparkle size={16} c="#2563EB"/></div>
            <div className="text-[13px] text-[#344054]">Japan_Air_Rates_Oct.xlsx — AI 识别到 <b className="tabnum">28</b> 条航线，<b className="tabnum">126</b> 条运价，<b className="tabnum text-[#B45309]">3</b> 个字段歧义，<b className="tabnum text-[#DC2626]">4</b> 条已过期</div>
          </div>
          <Btn size="sm" onClick={() => setImported(true)}>确认导入</Btn>
        </Card>
      ) : (
        <div className="bg-[#EFFBF1] text-[#16A34A] text-[13px] font-semibold rounded-lg px-4 py-3 mb-6">导入成功，126 条运价已更新到下方列表。</div>
      )}

      <Card hover={false} className="overflow-hidden">
        <div className="grid grid-cols-8 px-5 py-3 bg-[#F7F8FA] border-b border-[#E4E7EC] text-[11px] font-bold text-[#667085]">
          <span>起运地</span><span>目的地</span><span>模式</span><span>计价单位</span><span>价格</span><span>附加费</span><span>有效期</span><span>状态</span>
        </div>
        {rates.map((row, i) => (
          <div key={i} className={`grid grid-cols-8 px-5 py-3.5 items-center text-[13px] ${i < rates.length - 1 ? 'border-b border-[#F1F3F6]' : ''}`}>
            {row.slice(0, 6).map((c, j) => <span key={j} className={j >= 4 ? 'tabnum font-semibold' : 'text-[#344054]'}>{c}</span>)}
            <span className="tabnum text-[#344054]">{row[6]}</span>
            <span className={`text-[11px] font-bold px-2 py-0.5 rounded-full w-fit ${row[7] === '有效' ? 'bg-[#EFFBF1] text-[#16A34A]' : row[7] === '已过期' ? 'bg-[#FDECEC] text-[#DC2626]' : 'bg-[#FFF7E8] text-[#B45309]'}`}>{row[7]}</span>
          </div>
        ))}
      </Card>
    </SupplierLayout>
  );
}

function SupplierCompanyPage() {
  return (
    <SupplierLayout active="公司主页">
      <div className="grid grid-cols-[1fr_320px] gap-6">
        <Card hover={false} className="p-6 flex flex-col gap-4">
          <div className="text-[13px] font-bold text-[#667085]">公司资料（来自入驻申请，可编辑）</div>
          <div className="grid grid-cols-2 gap-3.5 text-[13px]">
            <div><div className="text-[#98A2B3] mb-1">公司名称</div><div className="font-semibold">宁波蓝海国际货运代理有限公司</div></div>
            <div><div className="text-[#98A2B3] mb-1">认证状态</div><VerifiedBadge tier="verified" /></div>
            <div><div className="text-[#98A2B3] mb-1">服务类型</div><div className="font-semibold">空运、海运 LCL、DDP</div></div>
            <div><div className="text-[#98A2B3] mb-1">优势航线</div><div className="font-semibold">宁波 → 日本/韩国、宁波 → 北欧</div></div>
          </div>
          <div>
            <div className="text-[#98A2B3] text-[13px] mb-1">公司介绍</div>
            <textarea rows={4} defaultValue="专注日本、韩国及北欧航线空海运代理 10 年，自有日本目的港担保代理网络，支持一站式报关报检及清关服务。" className="w-full border border-[#E4E7EC] rounded-lg px-3 py-2.5 text-[14px] resize-none"></textarea>
          </div>
          <Btn size="sm" className="w-fit">保存修改</Btn>
        </Card>
        <Card hover={false} className="p-5 h-fit">
          <div className="text-[13px] font-bold text-[#667085] mb-3">前台展示</div>
          <p className="text-[12px] text-[#667085] leading-relaxed mb-4">这些信息会展示在客户看到的货代目录主页上，信息越完整，客户的信任度和询盘转化率越高。</p>
          <Btn to="/forwarders/bluewave-logistics" variant="outline" className="w-full">预览前台主页</Btn>
        </Card>
      </div>
    </SupplierLayout>
  );
}
const ROUTE_TABLE = [
  { pattern: '/', element: <CustomerLayout><HomePage /></CustomerLayout> },
  { pattern: '/quote', element: <CustomerLayout><QuotePage /></CustomerLayout> },
  { pattern: '/quote/results', element: <CustomerLayout><QuoteResultsPage /></CustomerLayout> },
  { pattern: '/quote/:id', element: <CustomerLayout><QuoteDetailPage /></CustomerLayout> },
  { pattern: '/rfq', element: <CustomerLayout><RFQMarketPage /></CustomerLayout> },
  { pattern: '/rfq/new', element: <CustomerLayout><PostRFQPage /></CustomerLayout> },
  { pattern: '/rfq/:id', element: <CustomerLayout><RFQDetailPage /></CustomerLayout> },
  { pattern: '/forwarders', element: <CustomerLayout><DirectoryPage /></CustomerLayout> },
  { pattern: '/forwarders/:slug', element: <CustomerLayout><ForwarderProfilePage /></CustomerLayout> },
  { pattern: '/routes', element: <CustomerLayout><RoutesPage /></CustomerLayout> },
  { pattern: '/routes/:slug', element: <CustomerLayout><RouteDetailPage /></CustomerLayout> },
  { pattern: '/shipments', element: <CustomerLayout><ShipmentsPage /></CustomerLayout> },
  { pattern: '/shipments/:id', element: <CustomerLayout><ShipmentDetailPage /></CustomerLayout> },
  { pattern: '/ai', element: <CustomerLayout><AIAssistantPage /></CustomerLayout> },
  { pattern: '/login', element: <CustomerLayout><AuthPage /></CustomerLayout> },
  { pattern: '/pricing', element: <CustomerLayout><PricingPage /></CustomerLayout> },
  { pattern: '/about', element: <CustomerLayout><AboutPage /></CustomerLayout> },
  { pattern: '/trust-safety', element: <CustomerLayout><TrustSafetyPage /></CustomerLayout> },
  { pattern: '/news', element: <CustomerLayout><NewsPage /></CustomerLayout> },
  { pattern: '/news/:slug', element: <CustomerLayout><NewsArticlePage /></CustomerLayout> },
  { pattern: '/contact', element: <CustomerLayout><ContactPage /></CustomerLayout> },
  { pattern: '/supplier/onboarding', element: <SupplierOnboardingPage /> },
  { pattern: '/supplier/dashboard', element: <SupplierDashboardPage /> },
  { pattern: '/supplier/rfq/:id', element: <SupplierRFQSubmitPage /> },
  { pattern: '/supplier/rates', element: <SupplierRatesPage /> },
  { pattern: '/supplier/company', element: <SupplierCompanyPage /> },
];

function App() {
  return <AppRouter routes={ROUTE_TABLE} />;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
