'use client';

import React from 'react';
import Image from 'next/image';
import * as cheerio from 'cheerio';

interface PageData {
  title?: string;
  description?: string;
}

interface LogisticsClientProps {
  pageData: PageData | null;
}

const LogisticsTable: React.FC<LogisticsClientProps> = ({ pageData }) => {
  if (!pageData) {
    return (
      <div className="min-h-screen bg-gray-50 py-12 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-semibold text-gray-700">Loading logistics information...</h2>
        </div>
      </div>
    );
  }

  // ✅ Use Cheerio for SSR-safe HTML parsing
  const parseTableData = (html: string) => {
    const $ = cheerio.load(html);
    const table = $('table');
    if (!table.length) return null;

    const headers = table.find('thead th').map((_, th) => $(th).html()?.trim() || '').get();
    const rows = table.find('tbody tr').map((_, tr) =>
      $(tr).find('td').map((_, td) => $(td).html()?.trim() || '').get()
    ).get();

    // Fix: rows returned flat by default, so chunk them
    const chunkedRows: string[][] = [];
    for (let i = 0; i < rows.length; i += headers.length) {
      chunkedRows.push(rows.slice(i, i + headers.length));
    }

    return { headers, rows: chunkedRows };
  };

  const tableData = pageData.description ? parseTableData(pageData.description) : null;

  if (!tableData) {
    return (
      <div className="min-h-screen bg-gray-50 py-12">
        <section className="mx-auto max-w-6xl px-4 md:px-6 lg:px-8">
          <h2 className="text-4xl font-normal mb-10 text-[#112f41]">{pageData.title || 'Logistics'}</h2>
          <div className="bg-white p-6 rounded-lg shadow-md">
            <p>No table data available.</p>
          </div>
        </section>
      </div>
    );
  }

  // Function to render cell content with bullet images
  const renderCellContent = (cell: string) => {
    if (cell === '&nbsp;' || cell === '') return null;

    if (cell.includes('<strong>') || cell.startsWith('Ports') || cell.startsWith('Facilities')) {
      return <div dangerouslySetInnerHTML={{ __html: cell }} />;
    }

    return (
      <div className="flex items-start gap-2 text-[15px]">
        <Image
          src="/assets/images/bullet.png"
          alt="•"
          width={16}
          height={16}
          className="mt-1 flex-shrink-0"
        />
        <span dangerouslySetInnerHTML={{ __html: cell }} />
      </div>
    );
  };

  return (
    <div className="min-h-screen  py-12">
      <section className="mx-auto max-w-6xl px-4 md:px-6 lg:px-8">
        <h2 className="text-[28px] md:text-[36px] font-[300] mb-10 text-[#112f41]">{pageData.title || 'Logistics'}</h2>

        <div className="bg-white rounded-lg shadow-md">
          <table className="min-w-full">
            <thead>
              <tr className="bg-gray-100">
                {tableData.headers.map((header, index) => (
                  <th key={index} className="px-4 py-3 text-left font-semibold text-[#112f41] text-lg"
                      dangerouslySetInnerHTML={{ __html: header }} />
                ))}
              </tr>
            </thead>
            <tbody>
              {tableData.rows.map((row, rowIndex) => (
                <tr key={rowIndex} className={rowIndex % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                  {row.map((cell, cellIndex) => (
                    <td key={cellIndex} className="px-4 py-3">
                      {renderCellContent(cell)}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
};

export default LogisticsTable;
