'use client';

import { useRef, useState } from 'react';
import Select from 'react-select';
import {
  PiX,
  PiCheckCircleFill,
  PiClockCountdown,
  PiLockKeyFill,
  PiHouse,
  PiCompass,
  PiRuler,
  PiCurrencyInr,
  PiWrench,
  PiUser,
  PiClipboardText,
  PiShieldCheck,
  PiCaretLeft,
  PiCaretRight,
  PiChat,
  PiArrowRight,
} from 'react-icons/pi';
import { useDrawer } from '@/components/common/Drawer';
import PrimaryButton from '@/components/common/primary-button';
import Timeline, { TimelineItem } from '@/components/common/timeline';

// ── Types ──────────────────────────────────────────────────────────────
type InventoryStatus = 'Available' | 'Booked' | 'Reserved' | 'Blocked';

interface Unit {
  id: number;
  unitNum: string;
  towerBlock: string;
  bhk: string;
  sqft: number;
  facing: string;
  status: InventoryStatus;
  constructionStage: string;
  qualityDefects: string;
  basePrice: number;
}

type Tab = 'unit' | 'crm' | 'quality' | 'audit';

type Severity = 'Low' | 'Medium' | 'High';
type SnagState = 'Open' | 'Resolved' | 'Closed';

interface Snag {
  id: string;
  description: string;
  team: string;
  severity: Severity;
  state: SnagState;
  by: string;
  date: string;
}

// ── Status config ──────────────────────────────────────────────────────
const STATUS_CONFIG: Record<InventoryStatus, {
  bg: string; text: string; label: string; icon: React.ReactNode;
}> = {
  Available: {
    bg: 'bg-emerald-50 border border-emerald-200',
    text: 'text-emerald-600',
    label: 'Available',
    icon: <PiCheckCircleFill size={22} className="text-emerald-500" />,
  },
  Reserved: {
    bg: 'bg-yellow-50 border border-yellow-200',
    text: 'text-yellow-600',
    label: 'Reserved',
    icon: <PiClockCountdown size={22} className="text-yellow-500" />,
  },
  Booked: {
    bg: 'bg-red-50 border border-red-200',
    text: 'text-red-500',
    label: 'Booked',
    icon: <PiLockKeyFill size={22} className="text-red-400" />,
  },
  Blocked: {
    bg: 'bg-gray-100 border border-gray-200',
    text: 'text-gray-500',
    label: 'Blocked',
    icon: <PiLockKeyFill size={22} className="text-gray-400" />,
  },
};

const TABS: { key: Tab; label: string }[] = [
  { key: 'unit', label: 'Unit Specifications' },
  { key: 'crm', label: 'CRM Customer Link' },
  { key: 'quality', label: 'Quality Checks / Defect Snags' },
  { key: 'audit', label: 'Audit Log Space' },
];


// ── Severity badge config ──────────────────────────────────────────────
const SEVERITY_STYLES: Record<Severity, string> = {
  Low:    'bg-gray-100 text-gray-500 border border-gray-200',
  Medium: 'bg-yellow-100 text-yellow-700 border border-yellow-200',
  High:   'bg-red-100 text-red-600 border border-red-200',
};

const STATE_STYLES: Record<SnagState, string> = {
  Open:     'border border-red-300 text-red-500 hover:bg-red-50',
  Resolved: 'border border-gray-300 text-gray-600 hover:bg-gray-50',
  Closed:   'border border-gray-300 text-gray-600 hover:bg-gray-50',
};

const ACTIVE_STATE_STYLES: Record<SnagState, string> = {
  Open:     'bg-red-500 text-white border-red-500',
  Resolved: 'bg-gray-700 text-white border-gray-700',
  Closed:   'bg-gray-400 text-white border-gray-400',
};



// ── Helper ─────────────────────────────────────────────────────────────
function getFloorLevel(unitNum: string): string {
  const match = unitNum.match(/[A-Z]-(\d)/);
  if (!match) return 'Floor Level 1';
  return `Floor Level ${match[1]}`;
}

function getPerSqftRate(basePrice: number, sqft: number): string {
  return Math.round(basePrice / sqft).toLocaleString('en-IN');
}

// ── Spec Info Box ──────────────────────────────────────────────────────
function SpecBox({ label, value }: { label: string; value: string }) {
  return (
    <div className="border border-gray-200 rounded-lg px-4 py-3 bg-white">
      <p className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-1">{label}</p>
      <p className="text-sm font-bold text-gray-800">{value}</p>
    </div>
  );
}

function SnagCard({
  snag,
  onStateChange,
}: {
  snag: Snag;
  onStateChange: (id: string, state: SnagState) => void;
}) {
  return (
    <div className="border border-gray-200 rounded-xl p-4 bg-white">
      {/* Top row */}
      <div className="flex items-start justify-between mb-1">
        <div>
          <p className="text-xs text-gray-400 font-mono tracking-wide">
            ID: <span className="text-indigo-500 font-semibold">{snag.id}</span>
          </p>
          <p className="text-sm font-bold text-gray-800 mt-0.5">{snag.description}</p>
        </div>
        <span
          className={`text-xs font-bold uppercase tracking-widest px-2.5 py-1 rounded-md ${
            SEVERITY_STYLES[snag.severity]
          }`}
        >
          {snag.severity.toUpperCase()}
        </span>
      </div>
        <hr></hr>
      <div className="flex items-center justify-between mt-2 mb-3">
        <p className="text-xs text-gray-500 flex flex-col">
            Team:
            <span className="font-semibold text-gray-700">{snag.team}</span>
        </p>
        <p className="text-xs text-gray-400 flex flex-col">
            By:
            <span>{snag.by} • {snag.date}</span>
        </p>
      </div>

      <div className="flex items-center justify-end gap-2">
        <span className="text-xs text-gray-400 font-medium whitespace-nowrap">
          Change State:
        </span>
        <div className="flex gap-1.5">
          {(['Open', 'Resolved', 'Closed'] as SnagState[]).map((s) => (
            <button
              key={s}
              onClick={() => onStateChange(snag.id, s)}
              className={`text-xs font-semibold px-3 py-1 rounded-lg border transition ${
                snag.state === s
                  ? ACTIVE_STATE_STYLES[s]
                  : STATE_STYLES[s]
              }`}
            >
              {s}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}


// ── Unit Spec Tab Content ──────────────────────────────────────────────
function UnitSpecTab({ unit }: { unit: Unit }) {
  const statusCfg = STATUS_CONFIG[unit.status];
  const downPayment = Math.round(unit.basePrice * 0.2);
  const loanAmount = Math.round(unit.basePrice * 0.8);

  return (
    <div className="space-y-5">
      {/* Inventory Phase Status */}
      <div className={`flex items-center justify-between px-4 py-3.5 rounded-xl ${statusCfg.bg}`}>
        <div>
          <p className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-0.5">
            Inventory Phase Status
          </p>
          <p className={`text-base font-bold ${statusCfg.text}`}>{statusCfg.label}</p>
        </div>
        {statusCfg.icon}
      </div>

      {/* Physical Floor Plan Specs */}
      <div>
        <div className="flex items-center gap-2 mb-3">
          <PiRuler size={14} className="text-gray-400" />
          <p className="text-xs font-bold uppercase tracking-widest text-gray-500">
            Physical Floor Plan Specs
          </p>
        </div>
        <div className="grid grid-cols-2 gap-2">
          <SpecBox label="Layout Type" value={unit.bhk} />
          <SpecBox label="Vasthu Facing" value={unit.facing} />
          <SpecBox label="Carpentry Area" value={`${unit.sqft} SqFt`} />
          <SpecBox label="Per Sqft Rate" value={`₹${getPerSqftRate(unit.basePrice, unit.sqft)}/sqft`} />
        </div>
      </div>

      {/* Total Base Valuation */}
      <div className="bg-primary rounded-xl px-5 py-4 text-white">
        <div className="flex justify-between items-start mb-3">
          <div>
            <p className="text-xs font-bold uppercase tracking-widest text-slate-200 mb-1">
              Total Base Valuation (INR)
            </p>
            <p className="text-2xl font-black tracking-tight">
              ₹ {unit.basePrice.toLocaleString('en-IN')}
            </p>
          </div>
          <div className="text-right">
            <p className="text-xs font-bold uppercase tracking-widest text-slate-200 mb-1">
              Ready to Book
            </p>
            <p className="text-xs text-slate-100">Excludes statutory registration</p>
          </div>
        </div>
        <div className="border-t border-white/10 pt-3 grid grid-cols-2 gap-4">
          <div>
            <p className="text-xs font-bold uppercase tracking-widest text-slate-200 mb-0.5">
              Estimated Down Payment (20%)
            </p>
            <p className="text-sm font-bold text-white">₹ {downPayment.toLocaleString('en-IN')}</p>
          </div>
          <div>
            <p className="text-xs font-bold uppercase tracking-widest text-slate-200 mb-0.5">
              Est. Bank Loan Priority (80%)
            </p>
            <p className="text-sm font-bold text-white">₹ {loanAmount.toLocaleString('en-IN')}</p>
          </div>
        </div>
      </div>

      {/* Site Construction Tracker */}
      <div>
        <div className="flex items-center gap-2 mb-3">
          <PiWrench size={14} className="text-gray-400" />
          <p className="text-xs font-bold uppercase tracking-widest text-gray-500">
            Site Construction Tracker
          </p>
        </div>
        <div className="border border-gray-200 rounded-xl px-4 py-3 bg-white flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center">
              <PiHouse size={16} className="text-gray-500" />
            </div>
            <div>
              <p className="text-sm font-semibold text-gray-800">Construction Milestones</p>
              <p className="text-xs text-primary font-medium">
                Current Phase: {unit.constructionStage}
              </p>
            </div>
          </div>
          <button className="text-xs font-semibold px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 transition">
            Ongoing Inspection
          </button>
        </div>
      </div>
    </div>
  );
}

function CRMCustomerTab({ unit }: { unit: Unit }) {
    const [linkedCustomer, setLinkedCustomer] = useState<any>(null);
    const [selectedCustomer, setSelectedCustomer] = useState('');
    const [activeCategory, setActiveCategory] = useState<string>(unit.status);

    const categoryButtons: { label: string; activeColor: string }[] = [
        { label: 'Available', activeColor: 'bg-emerald-500 text-white border-emerald-500' },
        { label: 'Reserved',  activeColor: 'bg-yellow-500 text-white border-yellow-500' },
        { label: 'Blocked',   activeColor: 'bg-gray-500 text-white border-gray-500' },
        { label: 'Handed Over', activeColor: 'bg-blue-600 text-white border-blue-600' },
    ];
    
    const customerOptions = [
        { value: "Rohit Sharma", label: "Rohit Sharma" },
        { value: "Priya Mehta", label: "Priya Mehta" },
    ];

    return (
        <div className="space-y-5">
        {!linkedCustomer && (
            <>
            {/* Allocation Engine Info Box */}
            <div className="bg-indigo-50 border border-indigo-100 rounded-xl px-4 py-3.5">
                <div className="flex items-center gap-2 mb-1">
                <span className="text-sm"><PiChat/></span>
                <span className="text-sm font-semibold text-gray-800">Allocation Engine:</span>
                </div>
                <p className="text-xs text-gray-500 leading-relaxed">
                This flat is open and unreserved. Link a converted CRM client profile here to initiate
                legal agreements and map down payment schedule milestones.
                </p>
            </div>

            <div>
                <label className="text-xs font-bold uppercase tracking-widest text-gray-500 mb-2 block">
                Select Active Converted Client
                </label>
                <Select
                    options={customerOptions}
                    value={customerOptions.find(opt => opt.value === selectedCustomer)}
                    onChange={(selected) => setSelectedCustomer(selected?.value || "")}
                    placeholder="-- Choose Customer --"
                    className="text-sm"
                    classNamePrefix="react-select"
                />
            </div>

            <div className="flex gap-3">
                <button className="flex-1 border border-yellow-300 text-yellow-600 bg-yellow-50 rounded-xl py-2.5 text-sm font-semibold hover:bg-yellow-100 transition">
                Soft Hold / Reserve Unit
                </button>
                <button
                onClick={() => {
                    if (!selectedCustomer) return;
                    setLinkedCustomer({
                    name: selectedCustomer,
                    id: 'C-002',
                    initials: selectedCustomer.split(' ').map(w => w[0]).join('').toUpperCase(),
                    handler: 'Amit Verma (Sales Manager)',
                    bookedOn: '2026-05-21  11:34  AM',
                    });
                    setActiveCategory('Reserved');
                }}
                className="flex-1 bg-gradient-to-r from-blue-800 to-emerald-400 text-white rounded-xl py-2.5 text-sm font-semibold hover:opacity-90 transition"
                >
                Assign Booked Client
                </button>
            </div>

            {/* Update Flat Category (empty state) */}
            <div>
                <p className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-3">
                Update Flat Category Category
                </p>
                <div className="flex gap-2">
                {categoryButtons.map(({ label, activeColor }) => (
                    <button
                    key={label}
                    onClick={() => setActiveCategory(label)}
                    className={`flex-1 py-2.5 text-xs font-semibold rounded-xl border transition ${
                        activeCategory === label
                        ? activeColor
                        : 'bg-white text-gray-500 border-gray-200 hover:border-gray-300'
                    }`}
                    >
                    {label}
                    </button>
                ))}
                </div>
            </div>
            </>
        )}
        {linkedCustomer && (
            <>
            <div className="border border-gray-200 rounded-xl px-5 py-4 bg-white">
                <div className="flex items-start justify-between gap-3">
                    <div className="flex items-start gap-3">
                        {/* Avatar */}
                        <div className="w-10 h-10 rounded-xl bg-indigo-600 text-white flex items-center justify-center text-sm font-bold flex-shrink-0">
                        {linkedCustomer.initials}
                        </div>

                        <div>
                        <span className="inline-block text-xs font-bold bg-indigo-100 text-indigo-600 px-2.5 py-0.5 rounded-full uppercase tracking-wide mb-1">
                            Linked Resident
                        </span>
                        <h3 className="text-sm font-bold text-gray-900 leading-tight">
                            {linkedCustomer.name}
                        </h3>
                        <p className="text-xs text-gray-400 mt-0.5">
                            Customer CRM Token Reference ID ID:{' '}
                            <span className="font-semibold text-gray-700">{linkedCustomer.id}</span>
                        </p>
                        </div>
                    </div>
                    <div className="flex gap-2 flex-shrink-0">
                        <button className="flex items-center gap-1.5 text-xs font-semibold border border-gray-200 text-gray-600 px-3 py-1.5 rounded-lg hover:bg-gray-50 transition">
                            CRM Profile
                            <span className="text-primary rounded-full border border-primary p-0.5"><PiArrowRight/></span>
                        </button>
                        <button
                        onClick={() => {
                            setLinkedCustomer(null);
                            setSelectedCustomer('');
                            setActiveCategory(unit.status);
                        }}
                        className="text-xs font-semibold border border-red-200 text-red-600 px-3 py-1.5 rounded-lg hover:bg-red-50 transition"
                        >
                        Release
                        </button>
                    </div>
                </div>
                <div className="mt-4 pt-3 border-t border-gray-100 grid grid-cols-2 gap-4">
                    <div>
                        <p className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-0.5">
                        Lead Handler
                        </p>
                        <p className="text-xs font-semibold text-gray-700">{linkedCustomer.handler}</p>
                    </div>
                    <div>
                        <p className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-0.5">
                        Book Date Timestamp
                        </p>
                        <p className="text-xs font-semibold text-gray-700">{linkedCustomer.bookedOn}</p>
                    </div>
                </div>
            </div>
            <div>
                <p className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-3">
                Update Flat Category Category
                </p>
                <div className="flex gap-2">
                {categoryButtons.map(({ label, activeColor }) => (
                    <button
                    key={label}
                    onClick={() => setActiveCategory(label)}
                    className={`flex-1 py-2.5 text-xs font-semibold rounded-xl border transition ${
                        activeCategory === label
                        ? activeColor
                        : 'bg-white text-gray-500 border-gray-200 hover:border-gray-300'
                    }`}
                    >
                    {label}
                    </button>
                ))}
                </div>
            </div>
            </>
        )}
        </div>
    );
}

function QualityChecksTab({ unit }: { unit: Unit }) {
  const [description, setDescription] = useState('');
  const [contractor, setContractor] = useState('UltraTech Civil Team');
  const [severity, setSeverity] = useState<Severity>('Low');

  const [snags, setSnags] = useState<Snag[]>([
    {
      id: `SNG-${Date.now() - 5000}`,
      description: 'Tile crack near bathroom entrance',
      team: 'UltraTech Concrete',
      severity: 'Low',
      state: 'Open',
      by: 'Site Engineer (JD)',
      date: '2026-05-23',
    },
    {
      id: `SNG-${Date.now() - 4000}`,
      description: 'Wall plaster seepage near window',
      team: 'Havells Electricals',
      severity: 'High',
      state: 'Open',
      by: 'Site Engineer (JD)',
      date: '2026-05-23',
    },
    {
      id: `SNG-${Date.now() - 3000}`,
      description: 'Bathroom seepage on south wall',
      team: 'L&T Construction',
      severity: 'Medium',
      state: 'Resolved',
      by: 'Site Engineer (JD)',
      date: '2026-05-23',
    },
    {
      id: `SNG-${Date.now() - 2000}`,
      description: 'Scratch on wall plaster near door',
      team: 'UltraTech Civil Team',
      severity: 'Low',
      state: 'Closed',
      by: 'Site Engineer (JD)',
      date: '2026-05-23',
    },
  ]);

  const handleSubmit = () => {
    if (!description.trim()) return;
    const newSnag: Snag = {
      id: `SNG-${Date.now()}`,
      description: description.trim(),
      team: contractor,
      severity,
      state: 'Open',
      by: 'Site Engineer (JD)',
      date: new Date().toISOString().split('T')[0],
    };
    setSnags((prev) => [newSnag, ...prev]);
    setDescription('');
  };

  const handleStateChange = (id: string, state: SnagState) => {
    setSnags((prev) =>
      prev.map((s) => (s.id === id ? { ...s, state } : s))
    );
  };

  return (
    <div className="space-y-5">

      {/* ── Log Form ── */}
      <div className="border border-gray-200 rounded-xl p-4 bg-white">
        <div className="flex items-center gap-2 mb-3">
          <span><PiWrench/></span>
          <p className="text-sm font-bold text-gray-800">Log Quality Rectification Snag</p>
        </div>

        <textarea
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Describe defect/fault (e.g. tile crack, bathroom seepage, scratch on wall plaster)..."
          rows={3}
          className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm text-gray-700 placeholder-gray-300 resize-none outline-none focus:ring-2 focus:ring-primary/20 mb-3"
        />
        <div className="flex items-center gap-2">
          <div className="flex-1">
            <label className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-1 block">
              Contractor Team
            </label>
            <select
              value={contractor}
              onChange={(e) => setContractor(e.target.value)}
              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-xs text-gray-700 bg-white outline-none focus:ring-2 focus:ring-primary/20"
            >
              <option>UltraTech Civil Team</option>
              <option>Havells Electricals</option>
              <option>L&T Construction</option>
              <option>UltraTech Concrete</option>
            </select>
          </div>

          <div className="flex-1">
            <label className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-1 block">
              Severity Flag
            </label>
            <select
              value={severity}
              onChange={(e) => setSeverity(e.target.value as Severity)}
              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-xs text-gray-700 bg-white outline-none focus:ring-2 focus:ring-primary/20"
            >
              <option value="Low">Low Concern</option>
              <option value="Medium">Medium Concern</option>
              <option value="High">High Concern</option>
            </select>
          </div>
          <div className="pt-5">
            <button
              onClick={handleSubmit}
              className="bg-[#0f1729] text-white text-xs font-bold px-4 py-2 rounded-lg hover:opacity-90 transition whitespace-nowrap"
            >
              Submit Log
            </button>
          </div>
        </div>
      </div>

      <div>
        <div className="flex items-center justify-between mb-3">
          <p className="text-xs font-bold uppercase tracking-widest text-gray-500">
            Defect Inspection History ({snags.length})
          </p>
        </div>

        <div className="space-y-3 max-h-72 overflow-y-auto pr-1">
          {snags.map((snag) => (
            <SnagCard
              key={snag.id}
              snag={snag}
              onStateChange={handleStateChange}
            />
          ))}
          {snags.length === 0 && (
            <div className="text-center py-10 text-gray-300 text-sm">
              No defects logged yet.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function AuditLogTab({ unit }: { unit: Unit }) {
  const auditItems: TimelineItem[] = [
    {
      id: 1,
      title: 'Local System View Session Launched',
      description: 'Staff JD (John Doe) requested audit overview of unit parameters.',
      date: '2026-02-21 11:34:58 UTC',
      icon: (
        <span className="w-3 h-3 rounded-full bg-gray-800 block" />
      ),
    },
    {
      id: 2,
      title: 'Quality Inspection Pre-check Passed',
      description: 'Site Engineer Sneha Reddy certified civil structural alignment checks standard.',
      date: '2026-02-07 15:42:00',
      icon: (
        <span className="w-3 h-3 rounded-full bg-indigo-500 block" />
      ),
    },
    {
      id: 3,
      title: 'Unit Master Creation',
      description: `Property initialized with base rate ₹${unit.basePrice.toLocaleString('en-IN')} under Galaxy Heights.`,
      date: '2023-10-10 11:30:00',
      icon: (
        <span className="w-3 h-3 rounded-full bg-emerald-500 block" />
      ),
    },
  ];

  return (
    <div className="space-y-5">

      {/* ── Compliance Banner ── */}
      <div className="border border-emerald-200 bg-emerald-50 rounded-xl px-4 py-3.5 flex items-start gap-2.5">
        <PiShieldCheck size={17} className="text-emerald-500 mt-0.5 flex-shrink-0" />
        <div>
          <p className="text-sm font-bold text-gray-800">
            Regulatory Ledger Audit Compliant
          </p>
          <p className="text-xs text-gray-500 mt-0.5 leading-relaxed">
            This property record is legally timestamped. All occupancy and valuation amendments are
            tracked below.
          </p>
        </div>
      </div>

      {/* ── Timeline ── */}
      <Timeline items={auditItems} />
    </div>
  );
}

// ── Placeholder Tabs ───────────────────────────────────────────────────
function PlaceholderTab({ label }: { label: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-gray-300">
      <PiClipboardText size={36} className="mb-3" />
      <p className="text-sm font-medium text-gray-400">{label}</p>
      <p className="text-xs text-gray-300 mt-1">No data available yet</p>
    </div>
  );
}

// ── Main Drawer Component ──────────────────────────────────────────────
export default function UnitSpecDrawer({ unit }: { unit: Unit }) {
    const { closeDrawer } = useDrawer();
    const [activeTab, setActiveTab] = useState<Tab>('unit');
    const tabRef = useRef<HTMLDivElement>(null);

    const scrollTabs = (direction: "left" | "right") => {
    if (!tabRef.current) return;

    const scrollAmount = 150;
        tabRef.current.scrollBy({
            left: direction === "left" ? -scrollAmount : scrollAmount,
            behavior: "smooth",
        });
    };

  return (
    <div className="flex flex-col h-full bg-white">
      <div className="bg-primary px-6 pt-5 pb-4 flex-shrink-0">
        <div className="flex items-start justify-between">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <span className="text-xs text-secondary px-2 py-0.5 font-semibold uppercase tracking-widest bg-slate-100 rounded-full border border-white">
                Galaxy Heights
              </span>
              <span className="text-white text-xs">•</span>
              <span className="text-xs text-secondary px-2 py-0.5 font-semibold uppercase tracking-widest bg-slate-100 rounded-full border border-white">
                {unit.towerBlock}
              </span>
            </div>
            <h2 className="text-xl font-black text-white tracking-tight">
              Unit {unit.unitNum}
            </h2>
            <p className="text-xs text-slate-100 mt-0.5">{getFloorLevel(unit.unitNum)}</p>
          </div>
          <button
            onClick={closeDrawer}
            className="w-7 h-7 rounded-full border border-white flex items-center justify-center text-gray-400 hover:text-white hover:border-white/40 transition"
          >
            <PiX size={14} className='text-white'/>
          </button>
        </div>
        <div className="relative mt-4">
            <button
                onClick={() => scrollTabs("left")}
                className="absolute left-0 top-1/2 -translate-y-1/2 z-10 bg-white/65 backdrop-blur px-2 py-2 rounded-full shadow hover:bg-white/20"
            >
                <PiCaretLeft />
            </button>
            <div
                ref={tabRef}
                className="overflow-hidden"
            >
                <div className="flex gap-3 border-b border-white/10 px-8">
                {TABS.map((tab) => (
                    <button
                    key={tab.key}
                    onClick={() => setActiveTab(tab.key)}
                    className={`text-sm font-semibold px-3 pb-2.5 pt-1 border-b-2 transition whitespace-nowrap ${
                        activeTab === tab.key
                        ? "border-white text-white"
                        : "border-transparent text-slate-200 hover:text-gray-300"
                    }`}
                    >
                    {tab.label}
                    </button>
                ))}
                </div>
            </div>
            <button
                onClick={() => scrollTabs("right")}
                className="absolute right-0 top-1/2 -translate-y-1/2 z-10 bg-white/65 backdrop-blur px-2 py-2 rounded-full shadow hover:bg-white/20"
            >
                <PiCaretRight />
            </button>
            </div>
      </div>
        <div className="flex-1 overflow-y-auto px-6 py-5">
            {!unit ? (
                <PlaceholderTab label="No unit selected" />
            ) : (
                <>
                {activeTab === 'unit'    && <UnitSpecTab unit={unit} />}
                {activeTab === 'crm'     && <CRMCustomerTab unit={unit} />}
                {activeTab === 'quality' && <QualityChecksTab unit={unit} />}
                {activeTab === 'audit'   && <AuditLogTab unit={unit} />}
                </>
            )}
        </div>

      {/* ── Footer ── */}
      <div className="flex justify-end gap-2 border-t border-gray-100 px-6 py-4 bg-white">
        <button
          onClick={closeDrawer}
          className="text-sm font-semibold text-gray-600 border border-gray-200 px-3 rounded-xl py-2.5 hover:bg-gray-50 transition"
        >
          Close Spec Panel
        </button>
        {(unit.status === 'Booked' || unit.status === 'Reserved') && (
            <PrimaryButton>
                Inspect Coverted Resident
            </PrimaryButton>
        )}
      </div>
    </div>
  );
}