import { useRef } from 'react';
import { Reveal } from '@/site/components/motion/reveal';
import { ArrowUpRight, Star } from '@/site/components/ui/icons';
import { RailControls } from '@/site/components/ui/rail-controls';
import { SectionHeading } from '@/site/components/ui/heading';
import { useRail } from '@/site/hooks/use-rail';
import { useShared } from '@/site/hooks/use-shared';
import { formatDate, useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';
import type { ReviewPlatform, Reviews } from '@/site/types';

/** Five stars, the first `rating` of them lit. Decorative: the rating is also written out. */
function Stars({ rating, className }: { rating: number; className?: string }) {
    return (
        <span
            aria-hidden="true"
            className={cx('flex gap-0.5 text-accent-fg', className)}
        >
            {[1, 2, 3, 4, 5].map((star) => (
                <Star
                    key={star}
                    className={cx(
                        'size-4',
                        star > Math.round(rating) && 'opacity-25',
                    )}
                />
            ))}
        </span>
    );
}

/** The clinic's profile on one platform: rating and count when entered, always a link. */
function PlatformCard({ platform }: { platform: ReviewPlatform }) {
    const { locale } = useShared();
    const t = useT();
    const copy = t.home.reviews;
    const name = copy.platforms[platform.key];
    const rating =
        platform.rating === null
            ? null
            : new Intl.NumberFormat(locale === 'tr' ? 'tr-TR' : 'en-GB', {
                  minimumFractionDigits: 1,
                  maximumFractionDigits: 1,
              }).format(platform.rating);

    return (
        <a
            href={platform.url}
            target="_blank"
            rel="noopener noreferrer"
            className="group border-line bg-stage-2 hover:border-accent-fg flex items-center justify-between gap-6 rounded-lg border px-6 py-5 transition-colors duration-300"
        >
            <span className="flex flex-col gap-1.5">
                <span className="font-semibold">{name}</span>
                {rating !== null && platform.rating !== null ? (
                    <span className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
                        <span className="font-display text-2xl leading-none">
                            {rating}
                        </span>
                        <Stars rating={platform.rating} />
                        <span className="sr-only">{copy.rating(rating)}</span>
                        {platform.count !== null ? (
                            <span className="text-soft">
                                {copy.count(platform.count)}
                            </span>
                        ) : null}
                    </span>
                ) : (
                    <span className="text-soft text-sm">{copy.read}</span>
                )}
            </span>
            <ArrowUpRight className="text-soft group-hover:text-accent-fg ease-out-expo size-5 shrink-0 transition-[transform,color] duration-500 group-hover:translate-x-0.5 group-hover:-translate-y-0.5" />
            <span className="sr-only"> ({t.common.newTab})</span>
        </a>
    );
}

/**
 * Patient reviews on the home page. With reviews copied from the platforms
 * (Admin → Yorumlar) it is a full section: the platform ratings and a row
 * of review cards. Without them, only a slim band linking to the clinic's
 * review pages. Nothing is shown while neither exists — no invented
 * reviews (docs/DECISIONS.md K11).
 */
export function ReviewsSection({ reviews }: { reviews: Reviews }) {
    const { locale } = useShared();
    const t = useT();
    const copy = t.home.reviews;
    const railRef = useRef<HTMLUListElement>(null);
    const rail = useRail(railRef);
    const { platforms, items } = reviews;

    if (platforms.length === 0 && items.length === 0) {
        return null;
    }

    if (items.length === 0) {
        return (
            // The space below belongs to the (light) section itself: the next
            // section starts without top padding.
            <section className="stage-light section-y-sm pt-0!">
                <div className="border-line border-y py-10">
                    <div className="shell flex flex-col gap-6 md:flex-row md:items-center md:justify-between">
                        <p className="font-display text-display-4">
                            {copy.band}
                        </p>
                        <ul className="grid gap-3 sm:grid-cols-2 md:flex">
                            {platforms.map((platform) => (
                                <li key={platform.key} className="md:min-w-64">
                                    <PlatformCard platform={platform} />
                                </li>
                            ))}
                        </ul>
                    </div>
                </div>
            </section>
        );
    }

    return (
        <section className="stage-light section-y">
            <div className="shell">
                <div className="flex flex-wrap items-end justify-between gap-8">
                    <SectionHeading
                        eyebrow={copy.eyebrow}
                        title={copy.title}
                        lead={copy.lead}
                    />
                    <RailControls rail={rail} />
                </div>

                {platforms.length > 0 ? (
                    <Reveal className="mt-10">
                        <ul className="grid gap-3 sm:grid-cols-2 lg:max-w-3xl">
                            {platforms.map((platform) => (
                                <li key={platform.key}>
                                    <PlatformCard platform={platform} />
                                </li>
                            ))}
                        </ul>
                    </Reveal>
                ) : null}
            </div>

            <ul
                ref={railRef}
                data-hscroll-track=""
                className="mt-10"
                aria-label={copy.eyebrow}
            >
                {items.map((review) => (
                    <li key={review.id} className="w-[82vw] sm:w-[24rem]">
                        <figure className="border-line bg-stage-2 flex h-full flex-col gap-5 rounded-lg border p-7">
                            {review.rating !== null ? (
                                <>
                                    <Stars rating={review.rating} />
                                    <span className="sr-only">
                                        {copy.rating(String(review.rating))}
                                    </span>
                                </>
                            ) : null}
                            <blockquote
                                lang={review.lang ?? undefined}
                                className="text-fg/85 grow text-[0.9375rem] leading-relaxed"
                            >
                                <p className="line-clamp-[9]">
                                    “{review.body}”
                                </p>
                            </blockquote>
                            <figcaption className="border-line flex items-end justify-between gap-4 border-t pt-4 text-sm">
                                <span>
                                    <span className="block font-semibold">
                                        {review.author}
                                    </span>
                                    <span className="text-soft">
                                        {review.source === 'other'
                                            ? null
                                            : copy.via(
                                                  copy.platforms[review.source],
                                              )}
                                        {review.date
                                            ? `${review.source === 'other' ? '' : ' · '}${formatDate(review.date, locale)}`
                                            : null}
                                    </span>
                                </span>
                                {review.url ? (
                                    <a
                                        href={review.url}
                                        target="_blank"
                                        rel="noopener noreferrer nofollow"
                                        className="text-accent-fg inline-flex shrink-0 items-center gap-1 font-medium"
                                    >
                                        {copy.original}
                                        <ArrowUpRight className="size-4" />
                                        <span className="sr-only">
                                            ({t.common.newTab})
                                        </span>
                                    </a>
                                ) : null}
                            </figcaption>
                        </figure>
                    </li>
                ))}
            </ul>
        </section>
    );
}
