import { Mail, Eye, Map as MapIcon, Users, Swords, ScrollText, CheckCircle2, Circle } from 'lucide-react';
import type { SystemId } from '@/lib/rules';
import type { Snapshot } from '@/lib/sync/messages';
import type { PlayerMap } from '@/lib/map';
import { useConditionGlossary } from '@/features/combat/useConditionGlossary';
import { usePlayerSessionStore } from '@/stores/playerSessionStore';
import { EmptyState } from '@/components/ui/Page';
import { Meter, Badge } from '@/components/ui/Codex';
import { cn } from '@/lib/cn';
import { PlayerMapView } from './PlayerMapView';

/** Presentational player view: battle map + party + initiative, from a snapshot. */
export function PlayerBoards({ snapshot, image, images }: { snapshot: Snapshot; image?: string; images?: Record<string, string> }) {
  const { party, encounter, map, handout } = snapshot;
  const quests = snapshot.quests ?? [];
  const condGlossary = useConditionGlossary((snapshot.system ?? '5e') as SystemId);
  const handoutImage = handout?.imageId ? images?.[handout.imageId] : undefined;
  const privateHandout = usePlayerSessionStore((s) => s.privateHandout);
  return (
    <>
      {privateHandout && (
        <section className="paper-grain mb-6 rounded-xl border border-info/60 bg-info/5 p-4">
          <div className="smallcaps mb-1 flex items-center gap-1.5 text-info">
            <Mail size={13} aria-hidden /> Just for you
          </div>
          <h2 className="font-display text-2xl font-bold text-ink">{privateHandout.title || 'A private note'}</h2>
          {privateHandout.body && <p className="mt-1 whitespace-pre-wrap text-ink">{privateHandout.body}</p>}
          {privateHandout.image && <img src={privateHandout.image} alt="" className="mt-3 max-h-[60vh] w-auto rounded-lg border border-line" />}
        </section>
      )}

      {handout && (
        <section className="mb-6 rounded-xl border border-accent/50 bg-accent-glow p-4">
          <div className="mb-1 flex items-center justify-between gap-2">
            <h2 className="font-display text-2xl font-bold text-accent-deep">{handout.title || 'Handout'}</h2>
            <Badge tone="gold"><Eye size={12} aria-hidden /> From the GM</Badge>
          </div>
          {handout.body && <p className="mt-1 whitespace-pre-wrap text-ink">{handout.body}</p>}
          {handoutImage && <img src={handoutImage} alt="" className="mt-3 max-h-[60vh] w-auto rounded-lg border border-line" />}
        </section>
      )}

      {map && (
        <section className="mb-6">
          <h2 className="smallcaps mb-2 flex items-center gap-1.5 text-muted">
            <MapIcon size={13} aria-hidden /> Battle map
          </h2>
          <PlayerMapView map={map as PlayerMap} image={image} images={images} viewportHeight="65vh" />
        </section>
      )}

      <div className="grid gap-6 lg:grid-cols-2">
        <section>
          <h2 className="smallcaps mb-2 flex items-center gap-1.5 text-muted">
            <Users size={13} aria-hidden /> Party
          </h2>
          {party.length === 0 ? (
            <p className="text-sm text-muted">No player characters.</p>
          ) : (
            <div className="space-y-2">
              {party.map((c) => {
                const pct = c.hp.max > 0 ? Math.max(0, Math.min(100, (c.hp.current / c.hp.max) * 100)) : 0;
                const portrait = c.imageId ? images?.[c.imageId] : undefined;
                const hpTone = pct > 50 ? 'var(--app-success)' : pct > 0 ? 'var(--app-warning)' : 'var(--app-danger)';
                return (
                  <div key={c.id} className="rounded-xl border border-line bg-panel p-3">
                    <div className="flex items-center justify-between gap-2">
                      <div className="flex min-w-0 items-center gap-2">
                        {portrait && <img src={portrait} alt="" className="h-9 w-9 shrink-0 rounded-full border border-line object-cover" />}
                        <span className="truncate font-display text-lg font-semibold text-ink">{c.name}</span>
                      </div>
                      <span className="shrink-0 font-mono text-xs text-muted">Lv {c.level} · AC {c.ac}</span>
                    </div>
                    <div className="mt-2">
                      <Meter value={c.hp.current} max={c.hp.max} tone={hpTone} height={10} />
                    </div>
                    <div className="mt-1 text-right font-mono text-xs text-muted">{c.hp.current}/{c.hp.max} HP{c.hp.temp > 0 ? ` (+${c.hp.temp})` : ''}</div>
                    {c.conditions.length > 0 && (
                      <div className="mt-1 flex flex-wrap gap-1">
                        {c.conditions.map((cond, i) => {
                          const tooltip = condGlossary.get(cond.name.toLowerCase());
                          return (
                            <span key={i} title={tooltip || undefined} className="cursor-help rounded-full bg-warning/15 px-2 py-0.5 text-xs text-warning">{cond.name}{cond.value ? ` ${cond.value}` : ''}</span>
                          );
                        })}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </section>

        <section>
          <h2 className="smallcaps mb-2 flex items-center gap-1.5 text-muted">
            <Swords size={13} aria-hidden /> Initiative {encounter ? `· Round ${encounter.round}` : ''}
          </h2>
          {!encounter ? (
            <EmptyState title="No active combat" hint="When the GM starts an encounter, the turn order shows here." />
          ) : (
            <ol className="space-y-1">
              {encounter.combatants.map((c) => (
                <li key={c.id} className={cn('flex items-center gap-3 rounded-xl border px-3 py-2', c.isCurrent ? 'border-accent bg-accent-glow ring-1 ring-accent/40' : 'border-line bg-panel')}>
                  <span className="w-8 text-center font-mono text-lg font-semibold text-accent-deep">{c.initiative}</span>
                  <span className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2">
                    <span className="font-display text-ink">{c.name}{c.isCurrent && <span className="ml-2 text-xs text-accent">◀ turn</span>}</span>
                    {c.conditions.map((cond, i) => (
                      <span key={i} className="rounded-full bg-warning/15 px-1.5 py-0.5 text-[10px] text-warning">{cond.name}{cond.value ? ` ${cond.value}` : ''}</span>
                    ))}
                  </span>
                  {c.hp ? (
                    <span className="shrink-0 font-mono text-sm text-muted">{c.hp.current}/{c.hp.max} HP</span>
                  ) : c.status ? (
                    <span className={cn('shrink-0 text-sm font-medium', c.status.cls)}>{c.status.label}</span>
                  ) : null}
                </li>
              ))}
            </ol>
          )}
        </section>
      </div>

      {quests.length > 0 && (
        <section className="mt-6">
          <h2 className="smallcaps mb-2 flex items-center gap-1.5 text-muted">
            <ScrollText size={13} aria-hidden /> Quest log
          </h2>
          <div className="grid gap-2 sm:grid-cols-2">
            {quests.map((q, qi) => (
              <div key={qi} className={cn('rounded-xl border border-line bg-panel p-3', q.completed && 'opacity-70')}>
                <div className="flex items-center gap-2">
                  {q.completed ? <CheckCircle2 size={15} className="text-success" aria-hidden /> : <Circle size={15} className="text-accent" aria-hidden />}
                  <span className={cn('font-display font-semibold text-ink', q.completed && 'line-through')}>{q.title}</span>
                </div>
                {q.objectives.length > 0 && (
                  <ul className="mt-1.5 space-y-0.5 pl-1 text-sm">
                    {q.objectives.map((o, oi) => (
                      <li key={oi} className={cn('flex items-start gap-1.5', o.done ? 'text-muted line-through' : 'text-ink')}>
                        <span className="mt-0.5 text-xs text-faint">{o.done ? '☑' : '☐'}</span>
                        <span>{o.text}</span>
                      </li>
                    ))}
                  </ul>
                )}
              </div>
            ))}
          </div>
        </section>
      )}
    </>
  );
}
