import { Head } from '@inertiajs/react';
import { Megaphone, Trophy, Zap } from 'lucide-react';

import DashboardLayout from '@/components/dashboard/DashboardLayout';
import { DashboardPageHeader } from '@/components/dashboard/DashboardPageHeader';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useTranslation } from '@/contexts/LanguageContext';

export default function ScoreApiGuide() {
    const { t } = useTranslation();

    return (
        <DashboardLayout>
            <Head title={t('Score API')} />

            <DashboardPageHeader
                title={t('Score API')}
                subtitle={t(
                    'Integrate your HTML5 game with the arcade leaderboard and interlevel ads via postMessage.',
                )}
            />

            <div className="space-y-6">
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Zap className="h-5 w-5" /> {t('Quick start')}
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3 text-sm">
                        <p>
                            {t(
                                'Your game runs inside an iframe on the play page. The arcade communicates with it via window.postMessage. Drop the helpers below into your game code, then call them at the right moments — no library needed.',
                            )}
                        </p>
                        <pre className="rounded-md bg-muted p-4 text-xs overflow-x-auto">
{`// Helpers — paste once into your game's bootstrap.
function reportScore(value, metadata, scoreType) {
    window.parent.postMessage(
        { type: 'score', value, metadata, score_type: scoreType },
        '*',
    );
}

function showInterlevelAd() {
    window.parent.postMessage(
        { type: 'show_interlevel_ad' },
        '*',
    );
}`}
                        </pre>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Trophy className="h-5 w-5" /> {t('Reporting scores')}
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3 text-sm">
                        <p>
                            {t(
                                'Call reportScore(value, metadata) whenever the player achieves a new score. The arcade inserts a row into game_scores for every submission and flips the is_personal_best flag onto whichever row holds the highest score for that (user, game) pair. Higher always wins — there is no "lower is better" mode today.',
                            )}
                        </p>
                        <pre className="rounded-md bg-muted p-4 text-xs overflow-x-auto">
{`// On final boss defeated:
reportScore(12450, { level: 8, time_seconds: 312 });

// On a checkpoint score:
reportScore(2300, { stage: 3, lives_left: 2 });`}
                        </pre>
                        <p>
                            <strong>{t('value')}</strong>{' '}
                            {t('must be a non-negative integer. The postMessage bridge floors floats client-side before sending; if you call the API directly, non-integer values are rejected with HTTP 422.')}{' '}
                            <strong>{t('metadata')}</strong>{' '}
                            {t('is an optional plain object stored on the score row as score_data. Useful for context (level, stage, time elapsed).')}{' '}
                            <strong>{t('scoreType')}</strong>{' '}
                            {t('is an optional ≤32-char tag (e.g. "time", "kills") that lets you keep multiple leaderboards per game.')}
                        </p>
                        <p className="text-muted-foreground">
                            {t(
                                'Scoring is gated by the per-game api_enabled flag. Toggle "Enable Score API" in the submit / edit form (only shown for HTML5 + embed game types). When off, POST /api/games/{gameId}/scores returns 422 with error="scoring_disabled" and reportScore() is a no-op. Anonymous users are never persisted.',
                            )}
                        </p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Megaphone className="h-5 w-5" /> {t('Interlevel ads')}
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3 text-sm">
                        <p>
                            {t(
                                'Call showInterlevelAd() at any natural break — between levels, on death, after a checkpoint, on the game-over screen. The arcade overlays an ad on top of your iframe; the player dismisses it manually with a Continue button.',
                            )}
                        </p>
                        <pre className="rounded-md bg-muted p-4 text-xs overflow-x-auto">
{`// Between levels:
function onLevelComplete() {
    saveProgress();
    showInterlevelAd();
}

// On death:
function onPlayerDied() {
    showInterlevelAd();
    showRetryScreen();
}`}
                        </pre>
                        <p>
                            {t(
                                "Don't spam this — once every 30–60 seconds is plenty. If no ad is configured for the slot, the overlay closes itself silently so showInterlevelAd is safe to call at every level boundary.",
                            )}
                        </p>
                        <p className="text-muted-foreground">
                            {t(
                                "For Flash, ROM, and TIC-80 games (where you can't edit the cart), the arcade fires interlevel ads on a per-placement timer. The operator configures the base delay under Ad Placements (default: 30s); each subsequent ad doubles the gap and only schedules after the player clicks Continue.",
                            )}
                        </p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>{t('Frequently asked')}</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3 text-sm">
                        <div>
                            <p className="font-medium">
                                {t("Why isn't my score showing on the leaderboard?")}
                            </p>
                            <p className="text-muted-foreground">
                                {t(
                                    "Three reasons in order of likelihood: (1) the Score API toggle is off in your game's submit/edit form, (2) the player isn't logged in (anonymous scores aren't persisted), or (3) postMessage origin issue — open the browser console and look for \"score\" type messages firing from your iframe.",
                                )}
                            </p>
                        </div>
                        <div>
                            <p className="font-medium">
                                {t('Can I test scoring locally?')}
                            </p>
                            <p className="text-muted-foreground">
                                {t(
                                    'Yes — embed your dev build at /play/{your-game-slug}. The arcade picks up postMessage events in any environment.',
                                )}
                            </p>
                        </div>
                        <div>
                            <p className="font-medium">
                                {t('Do I need to handle CORS?')}
                            </p>
                            <p className="text-muted-foreground">
                                {t(
                                    "No — postMessage works across origins by design. Just use '*' as the targetOrigin (we sanitize on receipt).",
                                )}
                            </p>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </DashboardLayout>
    );
}
