import React from 'react';
import Link from 'next/link';
import { cookies } from 'next/headers';
import { KeystoneLogoMinimal } from '../logo/keystone-logo-minimal';
import { LogoutButton } from './LogoutButton';
import { LoginModalController } from './LoginModalController';
import { MessageComposer } from './MessageComposer';
import { RowThumbnail } from './RowThumbnail';
import { PortalTabTracker } from './PortalTabTracker';
import {
  CONSUMER_TOKEN_COOKIE,
  fetchConsumerMe,
  fetchConsumerConversations,
  fetchConsumerMessages,
} from '../../lib/consumer-session';
import {
  getServices,
  getPackages,
  getCompanyInformation,
} from '../../lib/server-api';
import type { Message, ContactSummary } from '../../types/api/consumer';
import type { Service, ServiceItem } from '../../types/api/service';
import type { Package } from '../../types/api/package';
import type { OfferPublic } from '../../types/api/offer';

// ─── Types ────────────────────────────────────────────────────────────────────

interface SpecialItem {
  id: number;
  name: string;
  value_terms: string | null | undefined;
  expires_at: string | null | undefined;
  parentName: string;
  parentType: 'service' | 'package';
  photoAttachments: OfferPublic['photo_attachments'];
}

export interface PortalPageProps {
  searchParams?: Promise<Record<string, string>> | Record<string, string>;
  portalHref?: string;
  bookingHref?: string | null;
  bookingLabel?: string;
  /**
   * When true, always opens booking in a new tab even if the URL supports iframes.
   * Useful when the booking page's iframe experience is broken or undesirable.
   */
  forceExternalBooking?: boolean;
  /**
   * Path to the site's contact page, shown when no booking URL is configured.
   * Defaults to "/contact".
   */
  contactHref?: string;
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

/** HEAD-request the booking URL and inspect framing headers to decide whether to embed in an iframe. */
async function checkIframeAllowed(url: string): Promise<boolean> {
  try {
    const res = await fetch(url, {
      method: 'HEAD',
      redirect: 'follow',
      // Cache for 1 hour — booking platforms rarely change their embedding policy.
      next: { revalidate: 3600 },
    });

    const xfo = res.headers.get('x-frame-options')?.toUpperCase();
    if (xfo === 'DENY' || xfo === 'SAMEORIGIN') return false;

    const csp = res.headers.get('content-security-policy');
    if (csp) {
      const match = csp.match(/frame-ancestors\s+([^;]+)/i);
      if (match) {
        const policy = match[1].trim();
        if (policy === "'none'") return false;
      }
    }

    return true;
  } catch {
    return false;
  }
}

function formatCents(cents: number): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 0,
  }).format(cents / 100);
}

function formatTime(iso: string): string {
  return new Date(iso).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
}

function getInitials(str: string): string {
  return str.split(' ').map((w) => w[0]).join('').slice(0, 2).toUpperCase();
}

function aggregateSpecials(services: Service[], packages: Package[]): SpecialItem[] {
  const seen = new Set<number>();
  const specials: SpecialItem[] = [];

  for (const service of services) {
    for (const item of service.service_items ?? []) {
      for (const offer of item.offers ?? []) {
        if (offer.active === false || offer.expired) continue;
        if (seen.has(offer.id)) continue;
        seen.add(offer.id);
        specials.push({
          id: offer.id,
          name: offer.name,
          value_terms: offer.value_terms,
          expires_at: offer.expires_at,
          parentName: item.name,
          parentType: 'service',
          photoAttachments: item.photo_attachments,
        });
      }
    }
  }

  for (const pkg of packages) {
    for (const offer of pkg.offers ?? []) {
      if (offer.active === false || offer.expired) continue;
      if (seen.has(offer.id)) continue;
      seen.add(offer.id);
      specials.push({
        id: offer.id,
        name: offer.name,
        value_terms: offer.value_terms,
        expires_at: offer.expires_at,
        parentName: pkg.name,
        parentType: 'package',
        photoAttachments: pkg.photo_attachments,
      });
    }
  }

  return specials;
}

// ─── Shared sub-components ────────────────────────────────────────────────────

function LockButton({ label = 'View price' }: { label?: string }) {
  return (
    <button
      data-open-login-modal
      className="cursor-pointer rounded px-1.5 py-0.5 text-xs text-quaternary underline underline-offset-2 transition-colors hover:text-secondary"
    >
      {label}
    </button>
  );
}

function LoginWall({ message, cta }: { message: string; cta: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-20 text-center">
      <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-secondary">
        <svg className="size-5 text-quaternary" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z" />
        </svg>
      </div>
      <p className="text-sm font-medium text-primary">{message}</p>
      <button
        data-open-login-modal
        className="mt-4 cursor-pointer rounded-interactive bg-brand-solid px-5 py-2 text-sm font-semibold text-white transition-colors hover:bg-brand-solid_hover"
      >
        {cta}
      </button>
    </div>
  );
}

function EmptyState({ message }: { message: string }) {
  return (
    <div className="rounded-component border border-secondary bg-secondary py-16 text-center">
      <p className="text-sm text-tertiary">{message}</p>
    </div>
  );
}

// ─── Services Panel ───────────────────────────────────────────────────────────

function ServiceItemRow({
  item,
  isLoggedIn,
  specialsHref,
}: {
  item: ServiceItem;
  isLoggedIn: boolean;
  specialsHref: string;
}) {
  const activeOffers = (item.offers ?? []).filter((o) => o.active !== false && !o.expired);
  return (
    <div className="group flex items-center gap-3 px-4 py-3">
      <RowThumbnail
        photoAttachments={item.photo_attachments}
        seed={`item-${item.id}`}
        alt={item.name}
      />
      <div className="flex-1 min-w-0 flex items-center justify-between gap-3">
        <div className="min-w-0">
          <p className="text-base font-medium text-primary">{item.name}</p>
          {item.summary && <p className="mt-0.5 text-sm text-tertiary">{item.summary}</p>}
          {item.duration_minutes != null && item.duration_minutes > 0 && (
            <p className="mt-0.5 text-xs text-quaternary">{item.duration_minutes} min</p>
          )}
          {activeOffers.length > 0 && (
            <div className="mt-1.5 flex flex-wrap gap-1">
              {activeOffers.map((offer) =>
                isLoggedIn ? (
                  <Link
                    key={offer.id}
                    href={specialsHref}
                    className="inline-flex items-center rounded-badge bg-secondary border border-brand px-2 py-0.5 text-xs font-medium text-brand-secondary hover:bg-secondary_hover transition-colors"
                  >
                    Special: {offer.name}
                  </Link>
                ) : (
                  <button
                    key={offer.id}
                    data-open-login-modal
                    data-login-redirect={specialsHref}
                    className="inline-flex items-center rounded-badge bg-secondary border border-brand px-2 py-0.5 text-xs font-medium text-brand-secondary hover:bg-secondary_hover transition-colors cursor-pointer"
                  >
                    Special: {offer.name}
                  </button>
                )
              )}
            </div>
          )}
        </div>
        <div className="shrink-0 text-right">
          {isLoggedIn ? (
            item.price_cents != null ? (
              <span className="text-sm font-semibold text-primary">{formatCents(item.price_cents)}</span>
            ) : item.pricing_info ? (
              <span className="text-sm text-secondary">{item.pricing_info}</span>
            ) : null
          ) : (item.price_cents != null || item.pricing_info) ? (
            <LockButton />
          ) : null}
        </div>
      </div>
    </div>
  );
}

function ServicesPanel({
  services,
  isLoggedIn,
  portalHref,
}: {
  services: Service[];
  isLoggedIn: boolean;
  portalHref: string;
}) {
  const activeServices = services.filter((s) => (s.service_items?.length ?? 0) > 0);
  const specialsHref = `${portalHref}?tab=specials`;

  if (activeServices.length === 0) {
    return <EmptyState message="No services listed yet." />;
  }

  return (
    <>
      <PortalTabTracker event="ViewContent" params={{ contentName: 'Services', contentCategory: 'Services' }} />
      <div className="divide-y divide-tertiary rounded-component border border-secondary bg-primary overflow-hidden">
        {activeServices.map((service) => (
          <details key={service.id} className="group">
            <summary className="flex cursor-pointer list-none items-center justify-between px-5 py-4 hover:bg-secondary transition-colors">
              <div>
                <span className="font-medium text-primary">{service.name}</span>
                {service.summary && (
                  <p className="mt-0.5 text-sm text-tertiary">{service.summary}</p>
                )}
              </div>
              <div className="ml-4 flex items-center gap-2 shrink-0">
                <span className="text-xs text-quaternary">{service.service_items?.length ?? 0} items</span>
                <svg className="size-4 text-quaternary transition-transform group-open:rotate-180" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                </svg>
              </div>
            </summary>
            {service.service_items && service.service_items.length > 0 && (
              <div className="border-t border-tertiary bg-secondary divide-y divide-tertiary">
                {service.service_items.map((item) => (
                  <ServiceItemRow
                    key={item.id}
                    item={item}
                    isLoggedIn={isLoggedIn}
                    specialsHref={specialsHref}
                  />
                ))}
              </div>
            )}
          </details>
        ))}
      </div>
    </>
  );
}

// ─── Packages Panel ───────────────────────────────────────────────────────────

function PackagesPanel({
  packages,
  isLoggedIn,
  portalHref,
}: {
  packages: Package[];
  isLoggedIn: boolean;
  portalHref: string;
}) {
  const specialsHref = `${portalHref}?tab=specials`;

  if (packages.length === 0) return <EmptyState message="No packages available yet." />;

  return (
    <>
      <PortalTabTracker event="ViewContent" params={{ contentName: 'Packages', contentCategory: 'Packages' }} />
      <div className="grid gap-4 sm:grid-cols-2">
        {packages.map((pkg) => {
          const activeOffers = (pkg.offers ?? []).filter((o) => o.active !== false && !o.expired);
          return (
            <div key={pkg.id} className="group rounded-component border border-secondary bg-primary p-4 flex flex-col gap-3">
            <div className="flex items-start gap-3">
              <RowThumbnail
                photoAttachments={pkg.photo_attachments}
                seed={`pkg-${pkg.id}`}
                alt={pkg.name}
                sizeClassName="w-16 h-16"
              />
              <div className="flex-1 min-w-0 flex items-start justify-between gap-2">
                <div className="min-w-0">
                  <h4 className="font-semibold text-primary">{pkg.name}</h4>
                  {pkg.summary && <p className="mt-0.5 text-sm text-tertiary">{pkg.summary}</p>}
                </div>
                <div className="shrink-0 text-right">
                  {isLoggedIn ? (
                    pkg.price_cents != null ? (
                      <span className="text-xl font-bold text-primary">{formatCents(pkg.price_cents)}</span>
                    ) : pkg.pricing_info ? (
                      <span className="text-sm font-medium text-secondary">{pkg.pricing_info}</span>
                    ) : null
                  ) : (pkg.price_cents != null || pkg.pricing_info) ? (
                    <LockButton />
                  ) : null}
                </div>
              </div>
            </div>

            {pkg.package_items && pkg.package_items.length > 0 && (
              <ul className="space-y-1.5">
                {pkg.package_items.map((item, idx) => (
                  <li key={idx} className="flex items-center gap-2 text-sm text-secondary">
                    <span className="size-1.5 rounded-full bg-quaternary shrink-0" />
                    {item.quantity > 1 && <span className="font-medium text-primary">{item.quantity}×</span>}
                    {item.service_item?.name ?? '—'}
                  </li>
                ))}
              </ul>
            )}

            {activeOffers.length > 0 && (
              <div className="flex flex-wrap gap-1.5">
                {activeOffers.map((offer) =>
                  isLoggedIn ? (
                    <Link
                      key={offer.id}
                      href={specialsHref}
                      className="inline-flex items-center rounded-badge bg-secondary border border-brand px-2.5 py-0.5 text-xs font-medium text-brand-secondary hover:bg-secondary_hover transition-colors"
                    >
                      Special: {offer.name}
                    </Link>
                  ) : (
                    <button
                      key={offer.id}
                      data-open-login-modal
                      data-login-redirect={specialsHref}
                      className="inline-flex items-center rounded-badge bg-secondary border border-brand px-2.5 py-0.5 text-xs font-medium text-brand-secondary hover:bg-secondary_hover transition-colors cursor-pointer"
                    >
                      Special: {offer.name}
                    </button>
                  )
                )}
              </div>
            )}
            </div>
          );
        })}
      </div>
    </>
  );
}

// ─── Specials Panel ───────────────────────────────────────────────────────────

function SpecialsPanel({ specials }: { specials: SpecialItem[] }) {
  if (specials.length === 0) {
    return <EmptyState message="No active specials right now. Check back soon." />;
  }

  return (
    <>
      <PortalTabTracker event="ViewContent" params={{ contentName: 'Specials', contentCategory: 'Specials' }} />
      <div className="space-y-3">
        {specials.map((special) => (
          <div key={special.id} className="group flex items-start gap-3 rounded-component border border-secondary bg-primary px-4 py-4">
            <RowThumbnail
              photoAttachments={special.photoAttachments}
              seed={`special-${special.id}`}
              alt={special.parentName}
            />
            <div className="flex-1 min-w-0">
              <p className="font-semibold text-primary">{special.name}</p>
              {special.value_terms && (
                <p className="mt-0.5 text-sm text-secondary">{special.value_terms}</p>
              )}
              <p className="mt-1 text-xs text-quaternary">
                {special.parentType === 'service' ? 'Service' : 'Package'}: {special.parentName}
              </p>
              {special.expires_at && (
                <p className="mt-0.5 text-xs text-quaternary">
                  Expires {new Date(special.expires_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                </p>
              )}
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

// ─── Messages Panel ───────────────────────────────────────────────────────────

function MessagesPanel({
  messages,
  contactSummary,
  contactId,
  businessName,
}: {
  messages: Message[];
  contactSummary: ContactSummary | null;
  contactId: number | null;
  businessName: string;
}) {
  const threadBusiness =
    contactSummary?.business?.company_name ||
    contactSummary?.business?.name ||
    businessName;

  return (
    <div className="flex flex-col rounded-component border border-secondary bg-primary overflow-hidden">
      {/* Thread header */}
      <div className="flex items-center gap-2.5 border-b border-secondary px-4 py-3 shrink-0">
        <div className="flex h-7 w-7 items-center justify-center rounded-full bg-brand-solid text-xs font-semibold text-white shrink-0">
          {getInitials(threadBusiness)}
        </div>
        <span className="text-sm font-semibold text-primary">{threadBusiness}</span>
      </div>

      {/* Scrollable message list */}
      <div className="overflow-y-auto px-4 py-4 space-y-3" style={{ height: '70vh' }}>
        {messages.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full py-16 text-center">
            <div className="mb-3 flex h-10 w-10 items-center justify-center rounded-full bg-secondary">
              <svg className="size-5 text-quaternary" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M8.625 12a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 01-2.555-.337A5.972 5.972 0 015.41 20.97a5.969 5.969 0 01-.474-.065 4.48 4.48 0 00.978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25z" />
              </svg>
            </div>
            <p className="text-sm font-medium text-primary">No messages yet</p>
            <p className="mt-1 text-xs text-tertiary">Send a message to start the conversation.</p>
          </div>
        ) : (
          messages.map((m) => {
            const isOutbound = m.direction === 'outbound';
            return (
              <div key={m.id} className={`flex ${isOutbound ? 'justify-start' : 'justify-end'}`}>
                <div className={`max-w-[80%] rounded-component px-4 py-2.5 text-sm ${
                  isOutbound ? 'bg-secondary text-primary' : 'bg-brand-solid text-white'
                }`}>
                  {m.sender_display_name && (
                    <p className="mb-0.5 text-xs font-medium opacity-60">{m.sender_display_name}</p>
                  )}
                  <p className="whitespace-pre-wrap leading-relaxed">{m.body || '—'}</p>
                  <p className="mt-1 text-right text-[10px] opacity-50">{formatTime(m.created_at)}</p>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* Composer — fixed to bottom of panel */}
      {contactId && <MessageComposer contactId={contactId} />}
    </div>
  );
}

// ─── Book Panel ───────────────────────────────────────────────────────────────

function BookPanel({
  bookingHref,
  bookingLabel,
  bookingAllowsIframe,
  isLoggedIn,
}: {
  bookingHref: string;
  bookingLabel: string;
  bookingAllowsIframe: boolean;
  isLoggedIn: boolean;
}) {
  if (!isLoggedIn) {
    return <LoginWall message="Continue to view booking options." cta="View Booking Options" />;
  }

  if (bookingAllowsIframe) {
    return (
      <>
        <PortalTabTracker event="InitiateCheckout" />
        <div className="rounded-component border border-secondary overflow-hidden" style={{ height: '70vh' }}>
          <iframe
            src={bookingHref}
            className="w-full h-full"
            title="Book appointment"
            allow="payment"
          />
        </div>
      </>
    );
  }

  return (
    <>
      <PortalTabTracker event="InitiateCheckout" />
      <div className="flex flex-col items-center justify-center py-20 text-center">
        <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-secondary">
          <svg className="size-5 text-quaternary" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 9v7.5" />
          </svg>
        </div>
        <p className="text-sm font-medium text-primary">Ready to book?</p>
        <p className="mt-1 text-sm text-tertiary">You&apos;ll be taken to our booking system.</p>
        <a
          href={bookingHref}
          target="_blank"
          rel="noopener noreferrer"
          className="mt-5 inline-flex items-center gap-2 rounded-interactive bg-brand-solid px-6 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-brand-solid_hover"
        >
          {bookingLabel}
          <svg className="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
          </svg>
        </a>
      </div>
    </>
  );
}

// ─── Main Portal Page (Self-Contained Async Server Component) ─────────────────

const VALID_TABS = ['services', 'packages', 'specials', 'messages', 'book'] as const;
type Tab = (typeof VALID_TABS)[number];

export async function PortalPage({
  searchParams,
  portalHref = '/portal',
  bookingHref,
  bookingLabel = 'Book Now',
  forceExternalBooking = false,
  contactHref = '/contact',
}: PortalPageProps) {
  const params = await searchParams ?? {};
  const tab: Tab = VALID_TABS.includes(params.tab as Tab) ? (params.tab as Tab) : 'services';
  const contactIdParsed = params.contact ? parseInt(params.contact, 10) : NaN;
  const contactId = Number.isFinite(contactIdParsed) ? contactIdParsed : null;

  const cookieStore = await cookies();
  const token = cookieStore.get(CONSUMER_TOKEN_COOKIE)?.value ?? null;

  // Fetch public data + consumer in parallel.
  // Conversations are always fetched when logged in — needed for display name and messages.
  const [services, packages, companyInformation, consumer, conversations] = await Promise.all([
    getServices(),
    getPackages(),
    getCompanyInformation(),
    token ? fetchConsumerMe(token) : Promise.resolve(null),
    token ? fetchConsumerConversations(token) : Promise.resolve([]),
  ]);

  const resolvedBookingHref =
    bookingHref ?? companyInformation?.external_management_url ?? null;

  // Auto-detect iframe support by inspecting the booking URL's framing headers.
  // Only runs when the book tab is active to avoid unnecessary requests.
  // Skipped entirely when forceExternalBooking is set.
  const bookingAllowsIframe =
    !forceExternalBooking && tab === 'book' && resolvedBookingHref
      ? await checkIframeAllowed(resolvedBookingHref)
      : false;

  const businessName =
    companyInformation?.company_name ||
    'Member Portal';

  const isLoggedIn = !!consumer;

  // Use the first conversation's contact_id to identify this business's contact —
  // conversations are filtered server-side via API key, so they're always scoped correctly.
  const resolvedContactId = contactId ?? conversations[0]?.contact_id ?? null;

  // Find display name from the contact linked to this business's conversation thread,
  // falling back to any known identifier on the consumer record.
  const businessContact = consumer?.contacts?.find((c) => c.id === resolvedContactId);
  const consumerDisplayName =
    businessContact?.display_name ||
    consumer?.contacts?.[0]?.display_name ||
    consumer?.primary_identifier ||
    consumer?.email ||
    consumer?.phone ||
    null;

  const messageData =
    token && tab === 'messages' && resolvedContactId
      ? await fetchConsumerMessages(token, resolvedContactId)
      : { messages: [], contact: null };

  const serviceList = services ?? [];
  const packageList = packages ?? [];
  const specials = aggregateSpecials(serviceList, packageList);

  const tabs: Array<{ id: Tab; label: string }> = [
    { id: 'services', label: 'Services' },
    { id: 'packages', label: 'Packages' },
    { id: 'specials', label: 'Specials' },
    { id: 'messages', label: 'Messages' },
    { id: 'book', label: bookingLabel },
  ];

  return (
    <div className="min-h-screen bg-primary">
      {/* Portal Header */}
      <div className="border-b border-secondary bg-primary sticky top-0 z-40 shrink-0">
        <div className="mx-auto max-w-4xl px-4 py-4">
          <div className="flex items-center justify-between gap-4">
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-widest text-quaternary">
                Member Portal
              </p>
              <h1 className="text-xl font-bold text-primary leading-tight">{businessName}</h1>
            </div>

            <div className="flex items-center gap-3">
              {isLoggedIn ? (
                <div className="flex items-center gap-3">
                  {consumerDisplayName && (
                    <div className="hidden sm:flex items-center gap-2 rounded-full border border-secondary bg-secondary px-3 py-1.5">
                      <div className="flex h-5 w-5 items-center justify-center rounded-full bg-brand-solid text-[9px] font-bold text-white shrink-0">
                        {getInitials(consumerDisplayName)}
                      </div>
                      <span className="text-xs font-medium text-secondary max-w-[120px] truncate">
                        {consumerDisplayName}
                      </span>
                    </div>
                  )}
                  <LogoutButton />
                </div>
              ) : (
                <button
                  data-open-login-modal
                  className="cursor-pointer rounded-interactive border border-secondary px-3 py-1.5 text-xs font-medium text-secondary hover:bg-secondary transition-colors"
                >
                  Sign in
                </button>
              )}

              <div className="flex items-center gap-1.5 border-l border-tertiary pl-3">
                <KeystoneLogoMinimal className="size-5" />
                <span className="hidden sm:block text-[10px] font-medium text-quaternary">Keystone</span>
              </div>
            </div>
          </div>

          {/* Tabs */}
          <div className="mt-4 flex gap-1 overflow-x-auto pb-px scrollbar-none">
            {tabs.map((t) => {
              const isActive = tab === t.id;
              const isGated = !isLoggedIn && (t.id === 'specials' || t.id === 'messages' || t.id === 'book');
              const href = `${portalHref}?tab=${t.id}`;
              const className = `shrink-0 rounded-interactive px-4 py-2 text-sm font-medium transition-colors whitespace-nowrap ${
                isActive ? 'bg-brand-solid text-white' : 'text-secondary hover:bg-secondary hover:text-primary'
              }`;
              if (isGated) {
                return (
                  <button
                    key={t.id}
                    data-open-login-modal
                    data-login-redirect={href}
                    className={className}
                  >
                    {t.label}
                  </button>
                );
              }
              return (
                <Link key={t.id} href={href} className={className}>
                  {t.label}
                </Link>
              );
            })}
          </div>
        </div>
      </div>

      {/* Tab Content */}
      <div className="mx-auto max-w-4xl px-4 py-8">
        {tab === 'services' && (
          <ServicesPanel services={serviceList} isLoggedIn={isLoggedIn} portalHref={portalHref} />
        )}
        {tab === 'packages' && (
          <PackagesPanel packages={packageList} isLoggedIn={isLoggedIn} portalHref={portalHref} />
        )}
        {tab === 'specials' && (
          isLoggedIn ? (
            <SpecialsPanel specials={specials} />
          ) : (
            <LoginWall message="Continue to view specials." cta="View Specials" />
          )
        )}
        {tab === 'messages' && (
          isLoggedIn ? (
            <MessagesPanel
              messages={messageData.messages}
              contactSummary={messageData.contact}
              contactId={resolvedContactId}
              businessName={businessName}
            />
          ) : (
            <LoginWall message="Continue to view your messages." cta="View Messages" />
          )
        )}
        {tab === 'book' && (
          resolvedBookingHref ? (
            <BookPanel
              bookingHref={resolvedBookingHref}
              bookingLabel={bookingLabel}
              bookingAllowsIframe={bookingAllowsIframe}
              isLoggedIn={isLoggedIn}
            />
          ) : (
            <div className="flex flex-col items-center justify-center py-20 text-center">
              <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-secondary">
                <svg className="size-5 text-quaternary" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 9v7.5" />
                </svg>
              </div>
              <p className="text-sm font-medium text-primary">Ready to book?</p>
              <p className="mt-1 text-sm text-tertiary max-w-xs">
                Give us a call or submit a request on our{' '}
                  <a href={contactHref} className="underline underline-offset-2 hover:text-primary transition-colors">contact page</a>
                {' '}and we&apos;ll get you scheduled.
              </p>
            </div>
          )
        )}
      </div>

      {/* Single login modal controller — listens for [data-open-login-modal] clicks */}
      <LoginModalController />
    </div>
  );
}
