// Közös felületelemek (Tailwind osztályokkal): gombok, kártyák, űrlapmezők, címkék, értesítési csengő, menü.
(() => {
  const { useEffect, useRef, useState } = React;

  const cx = (...classes) => classes.filter(Boolean).join(' ');

  // ---------- Alapelemek ----------

  const BUTTON_STYLES = {
    primary: 'bg-yellow-400 text-slate-900 hover:bg-yellow-300 disabled:bg-slate-200 disabled:text-slate-400',
    accent: 'bg-yellow-400 text-slate-900 hover:bg-yellow-300 disabled:bg-slate-200 disabled:text-slate-400',
    success: 'bg-green-700 text-white hover:bg-green-600 disabled:bg-slate-300',
    danger: 'bg-red-700 text-white hover:bg-red-600 disabled:bg-slate-300',
    outline: 'border border-slate-400 text-slate-800 hover:bg-slate-50 disabled:text-slate-400',
    dangerOutline: 'border border-red-600 text-red-700 hover:bg-red-50 disabled:text-slate-400',
    ghost: 'text-slate-700 hover:bg-slate-200 disabled:text-slate-400',
    outlineLight: 'border border-white/60 text-white hover:bg-white/10 disabled:opacity-50',
  };

  function Button({ variant = 'primary', size = 'md', className = '', ...props }) {
    const sizes = { sm: 'px-3 py-1.5 text-sm', md: 'px-4 py-2', lg: 'px-6 py-3 text-lg' };
    return (
      <button
        type="button"
        {...props}
        className={cx(
          'inline-flex items-center justify-center rounded-lg font-semibold transition disabled:cursor-not-allowed',
          sizes[size],
          BUTTON_STYLES[variant],
          className,
        )}
      />
    );
  }

  /** Gomb kinézetű hivatkozás. */
  function ButtonLink({ variant = 'primary', size = 'md', className = '', to, ...props }) {
    const sizes = { sm: 'px-3 py-1.5 text-sm', md: 'px-4 py-2', lg: 'px-6 py-3 text-lg' };
    return (
      <Link
        to={to}
        {...props}
        className={cx('inline-flex items-center justify-center rounded-lg font-semibold transition', sizes[size], BUTTON_STYLES[variant], className)}
      />
    );
  }

  function Card({ className = '', children, ...props }) {
    return (
      <div {...props} className={cx('rounded-xl border border-slate-200 bg-white p-4 shadow-sm sm:p-6', className)}>
        {children}
      </div>
    );
  }

  const ALERT_STYLES = {
    error: 'border-red-300 bg-red-50 text-red-900',
    info: 'border-sky-300 bg-sky-50 text-sky-900',
    success: 'border-green-300 bg-green-50 text-green-900',
    warning: 'border-amber-300 bg-amber-50 text-amber-900',
  };

  function Alert({ kind = 'info', children, className = '' }) {
    if (!children) return null;
    return (
      <div role={kind === 'error' ? 'alert' : 'status'} className={cx('rounded-lg border px-4 py-3', ALERT_STYLES[kind], className)}>
        {children}
      </div>
    );
  }

  const ErrorAlert = ({ error }) => (error ? <Alert kind="error" className="mb-4">{error}</Alert> : null);

  function Loading() {
    return (
      <div className="flex justify-center py-12" aria-label="Betöltés">
        <div className="h-10 w-10 animate-spin rounded-full border-4 border-slate-300 border-t-yellow-400" />
      </div>
    );
  }

  const INPUT_STYLES =
    'w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-base focus:border-yellow-500 focus:outline-none focus:ring-2 focus:ring-yellow-200';

  /** Címke + beviteli elem + hibaüzenet / segédszöveg. Az elem a children. */
  function Field({ label, error, help, children, className = '' }) {
    return (
      <label className={cx('block', className)}>
        <span className="mb-1 block text-sm font-medium text-slate-700">{label}</span>
        {children}
        {error ? <span className="mt-1 block text-sm text-red-700">{error}</span> : null}
        {!error && help ? <span className="mt-1 block text-sm text-slate-500">{help}</span> : null}
      </label>
    );
  }

  const TextInput = ({ error, className = '', ...props }) => (
    <input {...props} className={cx(INPUT_STYLES, error && 'border-red-500', className)} />
  );
  const TextArea = ({ error, className = '', ...props }) => (
    <textarea rows={3} {...props} className={cx(INPUT_STYLES, error && 'border-red-500', className)} />
  );
  const Select = ({ error, className = '', children, ...props }) => (
    <select {...props} className={cx(INPUT_STYLES, error && 'border-red-500', className)}>
      {children}
    </select>
  );

  // ---------- Címkék ----------

  const CHIP_COLORS = {
    blue: 'bg-blue-100 text-blue-900',
    amber: 'bg-amber-100 text-amber-900',
    indigo: 'bg-indigo-100 text-indigo-900',
    purple: 'bg-purple-100 text-purple-900',
    green: 'bg-green-100 text-green-900',
    gray: 'bg-slate-200 text-slate-700',
    red: 'bg-red-600 text-white',
    outline: 'border border-slate-300 text-slate-700',
  };

  const Chip = ({ color = 'gray', children }) => (
    <span className={cx('inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold', CHIP_COLORS[color])}>{children}</span>
  );

  const StatusChip = ({ status, kind = 'job' }) =>
    kind === 'quote' ? (
      <Chip color={QUOTE_STATUS_COLORS[status]}>{QUOTE_STATUS_LABELS[status] ?? status}</Chip>
    ) : (
      <Chip color={STATUS_COLORS[status]}>{STATUS_LABELS[status] ?? status}</Chip>
    );

  const URGENCY_COLORS = { EMERGENCY: 'red', WITHIN_24H: 'amber', FLEXIBLE: 'outline' };
  const UrgencyBadge = ({ urgency }) => <Chip color={URGENCY_COLORS[urgency]}>{URGENCY_SHORT[urgency] ?? urgency}</Chip>;

  /** Csillagok: csak megjelenítés, vagy (onChange megadva) kattintható. */
  function StarRating({ value, count, onChange }) {
    if (onChange) {
      return (
        <div className="flex gap-1" role="radiogroup" aria-label="Értékelés">
          {[1, 2, 3, 4, 5].map((star) => (
            <button
              key={star}
              type="button"
              onClick={() => onChange(star)}
              aria-label={`${star} csillag`}
              className={cx('text-3xl leading-none', star <= (value ?? 0) ? 'text-amber-400' : 'text-slate-300')}
            >
              ★
            </button>
          ))}
        </div>
      );
    }
    if (value === null || value === undefined) {
      return <span className="text-sm text-slate-500">Még nincs értékelés</span>;
    }
    return (
      <span className="inline-flex items-center gap-2">
        <span className="text-amber-400" aria-hidden="true">
          {'★'.repeat(Math.round(value))}
          <span className="text-slate-300">{'★'.repeat(5 - Math.round(value))}</span>
        </span>
        <span className="text-sm text-slate-600">
          {String(value).replace('.', ',')}
          {count !== undefined ? ` (${count})` : ''}
        </span>
      </span>
    );
  }

  // ---------- Megerősítő ablak ----------

  function ConfirmDialog({ open, title, text, confirmLabel = 'Igen', danger = false, busy = false, onConfirm, onCancel }) {
    if (!open) return null;
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" role="dialog" aria-modal="true">
        <div className="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
          <h2 className="text-xl font-bold">{title}</h2>
          <p className="mt-2 text-slate-600">{text}</p>
          <div className="mt-6 flex justify-end gap-2">
            <Button variant="ghost" onClick={onCancel} disabled={busy}>Mégse</Button>
            <Button variant={danger ? 'danger' : 'primary'} onClick={onConfirm} disabled={busy}>
              {busy ? 'Folyamatban…' : confirmLabel}
            </Button>
          </div>
        </div>
      </div>
    );
  }

  // ---------- Munkák és ajánlatok ----------

  function JobCard({ job, to, showQuoteCount = false, footer }) {
    return (
      <Link to={to} className="block h-full">
        <Card className="flex h-full flex-col gap-2 transition hover:border-yellow-400 hover:shadow-md">
          <div className="flex flex-wrap gap-1.5">
            <UrgencyBadge urgency={job.urgency} />
            <StatusChip status={job.status} />
            {showQuoteCount && <Chip color={job.quoteCount > 0 ? 'amber' : 'outline'}>{job.quoteCount ?? 0} ajánlat</Chip>}
          </div>
          <h3 className="text-lg font-semibold leading-snug">{job.title}</h3>
          <p className="text-sm text-slate-600">{job.category?.name}</p>
          <div className="mt-auto pt-2">
            <p className="text-sm">
              {job.city}
              {job.distanceKm !== undefined ? ` · ${formatDistance(job.distanceKm)}` : ''}
            </p>
            <p className="text-xs text-slate-500">{formatDateTime(job.createdAt)}</p>
            {footer}
          </div>
        </Card>
      </Link>
    );
  }

  const TIMELINE_STEPS = [
    ['NEW', 'Bejelentve'], ['QUOTED', 'Ajánlatok'], ['ACCEPTED', 'Elfogadva'],
    ['IN_PROGRESS', 'Folyamatban'], ['COMPLETED', 'Kész'], ['REVIEWED', 'Értékelve'],
  ];

  /** Állapot-idővonal; lemondott munkánál figyelmeztetés. */
  function JobTimeline({ status }) {
    if (status === 'CANCELLED') {
      return <Alert kind="warning">Ez a munka le lett mondva.</Alert>;
    }
    const active = TIMELINE_STEPS.findIndex(([value]) => value === status);
    return (
      <ol className="flex gap-1 overflow-x-auto">
        {TIMELINE_STEPS.map(([value, label], index) => (
          <li key={value} className="min-w-[4.5rem] flex-1 text-center">
            <div className={cx('mx-auto flex h-8 w-8 items-center justify-center rounded-full text-sm font-bold', index <= active ? 'bg-yellow-400 text-slate-900' : 'bg-slate-200 text-slate-500')}>
              {index < active || status === 'REVIEWED' ? '✓' : index + 1}
            </div>
            <div className={cx('mt-1 text-xs', index === active ? 'font-semibold text-slate-900' : 'text-slate-500')}>{label}</div>
          </li>
        ))}
      </ol>
    );
  }

  /** Ajánlatok táblázata az ügyfélnek. Az „Elfogadom” csak függő ajánlatnál jelenik meg, ha canAccept igaz. */
  function QuoteTable({ quotes, canAccept = false, onAccept, busyId = null }) {
    if (quotes.length === 0) {
      return <p className="text-slate-600">Még nem érkezett ajánlat. Értesítünk, amint egy szerelő ajánlatot küld.</p>;
    }
    return (
      <div className="overflow-x-auto rounded-xl border border-slate-200 bg-white">
        <table className="w-full text-left text-sm">
          <thead className="bg-slate-50 text-slate-600">
            <tr>
              <th className="p-3">Szerelő</th>
              <th className="p-3 text-right">Összeg</th>
              <th className="p-3">Anyag</th>
              <th className="p-3">Legkorábban</th>
              <th className="p-3">Állapot</th>
              <th className="p-3" />
            </tr>
          </thead>
          <tbody>
            {quotes.map((quote) => (
              <tr key={quote.id} className={cx('border-t border-slate-100 align-top', quote.status === 'WITHDRAWN' && 'opacity-55')}>
                <td className="p-3">
                  <Link to={`/electricians/${quote.electrician.id}`} className="font-medium text-amber-700 hover:underline">
                    {quote.electrician.companyName ?? quote.electrician.name}
                  </Link>
                  {quote.electrician.companyName && <div className="text-xs text-slate-500">{quote.electrician.name}</div>}
                  <StarRating value={quote.electrician.averageRating} count={quote.electrician.reviewCount} />
                  {quote.message && <p className="mt-1 text-slate-600">„{quote.message}”</p>}
                </td>
                <td className="whitespace-nowrap p-3 text-right font-bold">{formatHuf(quote.amountHuf)}</td>
                <td className="p-3">{quote.materialsIncluded ? 'Benne van' : 'Külön'}</td>
                <td className="whitespace-nowrap p-3">{formatDateTime(quote.earliestStart)}</td>
                <td className="p-3"><StatusChip kind="quote" status={quote.status} /></td>
                <td className="p-3 text-right">
                  {canAccept && quote.status === 'PENDING' && (
                    <Button size="sm" disabled={busyId !== null} onClick={() => onAccept(quote)}>
                      {busyId === quote.id ? 'Elfogadás…' : 'Elfogadom'}
                    </Button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  /** `datetime-local` mező értéke holnap 8:00-ra, helyi idő szerint. */
  function defaultStart() {
    const date = new Date(Date.now() + 24 * 60 * 60 * 1000);
    date.setHours(8, 0, 0, 0);
    const pad = (value) => String(value).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
  }

  function QuoteForm({ onSubmit, errors = {}, submitting = false }) {
    const [amount, setAmount] = useState('');
    const [materialsIncluded, setMaterialsIncluded] = useState(false);
    const [earliestStart, setEarliestStart] = useState(defaultStart);
    const [message, setMessage] = useState('');

    const submit = (event) => {
      event.preventDefault();
      onSubmit({
        amountHuf: Number(amount),
        materialsIncluded,
        earliestStart: new Date(earliestStart).toISOString(),
        message: message.trim() || null,
      });
    };

    return (
      <form onSubmit={submit} className="space-y-4">
        <Field label="Összeg (Ft)" error={errors.amountHuf} help="Egész forintban, pl. 18500">
          <TextInput type="number" min="1000" step="500" required value={amount} onChange={(e) => setAmount(e.target.value)} error={errors.amountHuf} />
        </Field>
        <label className="flex items-center gap-2">
          <input type="checkbox" className="h-4 w-4" checked={materialsIncluded} onChange={(e) => setMaterialsIncluded(e.target.checked)} />
          Az anyagköltség benne van az árban
        </label>
        <Field label="Legkorábbi kezdés" error={errors.earliestStart}>
          <TextInput type="datetime-local" required value={earliestStart} onChange={(e) => setEarliestStart(e.target.value)} error={errors.earliestStart} />
        </Field>
        <Field label="Üzenet az ügyfélnek (nem kötelező)" error={errors.message}>
          <TextArea value={message} onChange={(e) => setMessage(e.target.value)} error={errors.message} />
        </Field>
        <Button type="submit" disabled={submitting || !amount}>{submitting ? 'Küldés…' : 'Ajánlat küldése'}</Button>
      </form>
    );
  }

  function ReviewForm({ onSubmit, submitting = false }) {
    const [rating, setRating] = useState(null);
    const [comment, setComment] = useState('');

    return (
      <form
        onSubmit={(event) => {
          event.preventDefault();
          onSubmit({ rating, comment: comment.trim() || null });
        }}
        className="space-y-4"
      >
        <div>
          <p className="mb-1 text-sm text-slate-700">Hány csillagot adsz a szerelőnek?</p>
          <StarRating value={rating} onChange={setRating} />
        </div>
        <Field label="Vélemény (nem kötelező)">
          <TextArea value={comment} onChange={(e) => setComment(e.target.value)} />
        </Field>
        <Button type="submit" disabled={!rating || submitting}>{submitting ? 'Küldés…' : 'Értékelés elküldése'}</Button>
      </form>
    );
  }

  // ---------- Fejléc: értesítési csengő és menü ----------

  const POLL_INTERVAL_MS = 30_000;

  /** Az olvasatlanok számát 30 másodpercenként kéri le (egyszerűbb, mint a WebSocket). */
  function NotificationBell() {
    const [count, setCount] = useState(0);
    const [open, setOpen] = useState(false);
    const [items, setItems] = useState([]);
    const box = useRef(null);

    const refreshCount = async () => {
      try {
        setCount((await api.get('/notifications/unread-count')).count);
      } catch {
        // a csengő hibája ne zavarja az oldalt
      }
    };

    useEffect(() => {
      refreshCount();
      const timer = setInterval(refreshCount, POLL_INTERVAL_MS);
      return () => clearInterval(timer);
    }, []);

    useEffect(() => {
      if (!open) return undefined;
      const close = (event) => {
        if (box.current && !box.current.contains(event.target)) setOpen(false);
      };
      document.addEventListener('mousedown', close);
      return () => document.removeEventListener('mousedown', close);
    }, [open]);

    const toggle = async () => {
      const next = !open;
      setOpen(next);
      if (next) {
        try {
          setItems((await api.get('/notifications')).notifications.slice(0, 8));
        } catch {
          setItems([]);
        }
      }
    };

    const choose = async (notification) => {
      setOpen(false);
      if (!notification.readAt) {
        await api.post(`/notifications/${notification.id}/read`).catch(() => {});
        refreshCount();
      }
      if (notification.link) navigate(notification.link);
    };

    return (
      <div className="relative" ref={box}>
        <button type="button" onClick={toggle} aria-label={`Értesítések (${count} olvasatlan)`} className="relative rounded-lg p-2 text-xl hover:bg-white/10">
          🔔
          {count > 0 && (
            <span className="absolute -right-0.5 -top-0.5 rounded-full bg-amber-400 px-1.5 text-xs font-bold text-slate-900">{count > 99 ? '99+' : count}</span>
          )}
        </button>
        {open && (
          <div className="absolute right-0 z-40 mt-2 w-80 max-w-[90vw] rounded-xl border border-slate-200 bg-white text-slate-900 shadow-xl">
            <p className="border-b border-slate-200 px-4 py-3 font-semibold">Értesítések</p>
            {items.length === 0 ? (
              <p className="p-4 text-sm text-slate-500">Nincs értesítésed.</p>
            ) : (
              <ul>
                {items.map((notification) => (
                  <li key={notification.id}>
                    <button type="button" onClick={() => choose(notification)} className={cx('block w-full px-4 py-2 text-left hover:bg-slate-100', !notification.readAt && 'bg-yellow-50')}>
                      <span className={cx('block text-sm', !notification.readAt && 'font-semibold')}>{notification.title}</span>
                      <span className="text-xs text-slate-500">{formatDateTime(notification.createdAt)}</span>
                    </button>
                  </li>
                ))}
              </ul>
            )}
            <Link to="/notifications" onClick={() => setOpen(false)} className="block border-t border-slate-200 px-4 py-3 text-center text-sm font-semibold text-amber-700 hover:bg-slate-50">
              Összes értesítés
            </Link>
          </div>
        )}
      </div>
    );
  }

  const MENUS = {
    CUSTOMER: [['/customer', 'Bejelentéseim'], ['/customer/jobs/new', 'Új bejelentés']],
    ELECTRICIAN: [['/electrician', 'Közeli munkák'], ['/electrician/my-jobs', 'Vállalt munkáim'], ['/electrician/profile', 'Profilom']],
    ADMIN: [['/admin', 'Szerelők'], ['/admin/categories', 'Kategóriák']],
  };

  /** Fejléc az összes belső oldalon: ugyanaz a sötét stílus, mint a főoldalon, aktív menüpont sárga aláhúzással. */
  function NavBar() {
    const { user, logout } = useAuth();
    const { path } = React.useContext(RouteContext);

    const items = user ? MENUS[user.role] : [];
    // A leghosszabb illeszkedő menüpont az aktív (pl. /customer/jobs/new az „Új bejelentés”, nem a „Bejelentéseim”).
    const current = items
      .filter(([to]) => path === to || path.startsWith(`${to}/`))
      .sort((a, b) => b[0].length - a[0].length)[0]?.[0];

    return (
      <header className="sticky top-0 z-30 border-b border-white/10 bg-slate-950 text-white">
        <div className="mx-auto flex max-w-6xl flex-wrap items-center gap-x-4 gap-y-1 px-4 py-3">
          <Link to={user ? homePathFor(user.role) : '/'} className="flex items-center gap-2">
            <Icon name="bolt" className="h-9 w-9 text-yellow-400" />
            <span className="leading-tight">
              <span className="block text-xl font-bold">Villanyszerelő</span>
              <span className="hidden whitespace-nowrap text-xs text-slate-300 sm:block">Gyorsan. Könnyen. Megbízhatóan.</span>
            </span>
          </Link>

          <nav className="order-last flex w-full flex-wrap gap-1 lg:order-none lg:ml-6 lg:w-auto lg:flex-1">
            {items.map(([to, label]) => (
              <Link
                key={to}
                to={to}
                className={cx('border-b-2 px-3 py-2 text-sm font-medium hover:text-yellow-400', to === current ? 'border-yellow-400' : 'border-transparent')}
              >
                {label}
              </Link>
            ))}
          </nav>

          <div className="ml-auto flex items-center gap-2 lg:ml-0">
            {user ? (
              <>
                <NotificationBell />
                <span className="mx-1 hidden text-sm md:inline">{user.name}</span>
                <button
                  type="button"
                  className="rounded-lg bg-yellow-400 px-4 py-2 text-sm font-bold text-slate-900 hover:bg-yellow-300"
                  onClick={async () => {
                    await logout();
                    navigate('/');
                  }}
                >
                  Kilépés
                </button>
              </>
            ) : (
              <>
                <Link to="/login" className="rounded-lg border border-white/60 px-4 py-2 text-sm font-semibold hover:bg-white/10">Bejelentkezés</Link>
                <Link to="/register" className="rounded-lg bg-yellow-400 px-4 py-2 text-sm font-bold text-slate-900 hover:bg-yellow-300">Regisztráció</Link>
              </>
            )}
          </div>
        </div>
      </header>
    );
  }

  /** `bare`: a főoldal saját fejlécet és láblécet rajzol, ezért itt csak a tartalmat adjuk vissza. */
  function Layout({ children, bare = false }) {
    if (bare) {
      return children;
    }
    return (
      <div className="flex min-h-screen flex-col">
        <NavBar />
        <main className="mx-auto w-full max-w-6xl flex-1 px-3 py-6 sm:px-4 sm:py-8">{children}</main>
        <footer className="bg-slate-950 text-slate-300">
          <div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-5 text-sm">
            <p>
              <span className="font-semibold text-white">Villanyszerelő</span> · Gyorsan. Könnyen. Megbízhatóan.
            </p>
            <p className="text-xs text-slate-400">Szakdolgozati bemutató alkalmazás</p>
          </div>
        </footer>
      </div>
    );
  }

  /** Átirányít egy másik oldalra (a megjelenítés után, nem közben). */
  function Redirect({ to }) {
    useEffect(() => {
      navigate(to, { replace: true });
    }, [to]);
    return null;
  }

  /** Cím + gombok egy sorban (mobilon törik). */
  const PageHeader = ({ title, subtitle, children }) => (
    <div className="mb-6 flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-slate-950 px-5 py-5 text-white sm:px-8">
      <div>
        <h1 className="text-2xl font-extrabold sm:text-3xl">{title}</h1>
        {subtitle && <p className="mt-1 text-slate-300">{subtitle}</p>}
        <span className="mt-3 block h-1 w-12 rounded bg-yellow-400" />
      </div>
      {children}
    </div>
  );

  /** Képek kicsinyítve, kattintásra nagyban nyílnak. */
  const PhotoGrid = ({ photos }) =>
    photos.length > 0 ? (
      <div className="mt-4 flex flex-wrap gap-3">
        {photos.map((photo) => (
          <a key={photo.id} href={photo.url} target="_blank" rel="noreferrer">
            <img src={photo.url} alt="A bejelentéshez csatolt fotó" className="h-36 w-36 rounded-lg object-cover" />
          </a>
        ))}
      </div>
    ) : null;

  Object.assign(window, {
    cx, Button, ButtonLink, Card, Alert, ErrorAlert, Loading, Field, TextInput, TextArea, Select,
    Chip, StatusChip, UrgencyBadge, StarRating, ConfirmDialog, JobCard, JobTimeline, QuoteTable,
    QuoteForm, ReviewForm, Layout, PageHeader, PhotoGrid, Redirect, NotificationBell,
  });
})();
