const { useState } = React;

const SpecHeader = ({ spec, navLinks, activeNav, onNavChange, functionalities }) => {
  const [expanded, setExpanded] = useState(false);
  const totalReq = functionalities.reduce((sum, func) => sum + func.requirements.filter(r => r.level === "required").length, 0);
  const totalRec = functionalities.reduce((sum, func) => sum + func.requirements.filter(r => r.level === "recommended").length, 0);
  const totalAll = totalReq + totalRec || 1;

  const formatDate = (dateString) => {
    if (!dateString) return "";
    return new Date(dateString).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
  };

  const PersonList = ({ people }) => (
    <span>
      {people.map((person, index) => (
        <span key={person.identifier || `${person.name}-${index}`}>
          {person.identifier ? (
            <a
              href={`https://govstack.global/${person.identifier}`}
              target="_blank"
              rel="noopener noreferrer"
              className="text-indigo-600 hover:underline font-medium"
            >
              {person.name}
            </a>
          ) : (
            <span className="text-slate-700 font-medium">{person.name}</span>
          )}
          {person.affiliation && (
            <span className="text-slate-400">
              {" "}·{" "}
              <a href={person.affiliation.url} target="_blank" rel="noopener noreferrer" className="hover:underline text-slate-500">
                {person.affiliation.name}
              </a>
            </span>
          )}
          {index < people.length - 1 && <span className="text-slate-300 mx-1.5">·</span>}
        </span>
      ))}
    </span>
  );

  return (
    <div className="bg-white border-b border-slate-200">
      <div className="border-b border-slate-100 bg-slate-50 px-6 py-2">
        <div className="max-w-6xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-2 text-xs text-slate-500">
            <a href="https://govstack.global" target="_blank" rel="noopener noreferrer" className="font-semibold text-indigo-700 hover:underline">
              GovStack
            </a>
            <span className="text-slate-300">›</span>
            {spec.workingGroup ? (
              <a href={`https://govstack.global/${spec.workingGroup}`} target="_blank" rel="noopener noreferrer" className="hover:underline">
                {spec.bbName || "Working Group"}
              </a>
            ) : (
              <span className="text-slate-500">Working Group</span>
            )}
            <span className="text-slate-300">›</span>
            <span className="text-slate-700 font-medium">{spec.name || "Specification"}</span>
          </div>
          <span className="text-[10px] font-mono text-slate-400 hidden sm:block">
            {spec.identifier || spec.namespace || spec.bbKey || ""}
          </span>
        </div>
      </div>

      <div className="px-6 pt-5 pb-0 max-w-6xl mx-auto">
        <div className="flex items-start justify-between gap-6">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-3 mb-3 flex-wrap">
              <div className="w-10 h-10 rounded-xl bg-indigo-600 flex items-center justify-center text-white font-bold text-base flex-shrink-0">
                {spec.bbName ? spec.bbName.slice(0, 1).toUpperCase() : "S"}
              </div>
              <div>
                <h1 className="text-xl font-bold text-slate-900 leading-tight">{spec.name || "Specification Viewer"}</h1>
                <div className="flex items-center gap-2 mt-1 flex-wrap">
                  {spec.version && (
                    <span className="text-xs font-semibold text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-full border border-indigo-100">v{spec.version}</span>
                  )}
                  {spec.status && (
                    <span className="text-xs font-semibold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-100 capitalize">✓ {spec.status}</span>
                  )}
                  {spec.publishedDate && (
                    <span className="text-xs text-slate-400">Published {formatDate(spec.publishedDate)}</span>
                  )}
                </div>
              </div>
            </div>

            {spec.description && (
              <>
                <p className={`text-sm text-slate-600 leading-relaxed ${expanded ? "" : "line-clamp-2"}`}>
                  {spec.description}
                </p>
                <button onClick={() => setExpanded(value => !value)} className="text-xs text-indigo-500 hover:text-indigo-700 mt-1 font-medium">
                  {expanded ? "Show less ▲" : "Read more ▼"}
                </button>
              </>
            )}

            {expanded && (
              <div className="mt-4 space-y-2 text-xs pb-3 border-t border-slate-100 pt-3">
                {[
                  { label: "Authors", people: spec.authors },
                  { label: "Editors", people: spec.editors },
                  { label: "Reviewers", people: spec.reviewers },
                ].filter(group => group.people?.length).map(({ label, people }) => (
                  <div key={label} className="flex gap-3">
                    <span className="text-slate-400 font-medium w-16 flex-shrink-0">{label}</span>
                    <div className="leading-relaxed"><PersonList people={people} /></div>
                  </div>
                ))}
                {(spec.namespace || spec.identifier) && (
                  <div className="flex gap-3 pt-1">
                    <span className="text-slate-400 font-medium w-16 flex-shrink-0">URN</span>
                    <span className="font-mono text-slate-500 text-[11px] break-all">{spec.identifier || spec.namespace}</span>
                  </div>
                )}
              </div>
            )}
          </div>

          <div className="flex-shrink-0 bg-slate-50 border border-slate-200 rounded-xl p-4 min-w-[170px]">
            <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-3">At a Glance</div>
            <div className="space-y-2.5">
              <div className="flex items-center justify-between gap-6">
                <span className="text-xs text-slate-500">Functionalities</span>
                <span className="font-bold text-slate-800">{functionalities.length}</span>
              </div>
              <div className="flex items-center justify-between gap-6">
                <span className="text-xs text-slate-500">Required</span>
                <span className="font-bold text-rose-600">{totalReq}</span>
              </div>
              <div className="flex items-center justify-between gap-6">
                <span className="text-xs text-slate-500">Recommended</span>
                <span className="font-bold text-amber-600">{totalRec}</span>
              </div>
              <div className="h-px bg-slate-200" />
              <div className="flex items-center justify-between gap-6">
                <span className="text-xs text-slate-500">Total</span>
                <span className="font-bold text-slate-800">{totalReq + totalRec}</span>
              </div>
            </div>
            <div className="flex rounded-full overflow-hidden h-1.5 mt-3 bg-slate-200">
              <div className="bg-rose-400" style={{ width: `${Math.round((totalReq / totalAll) * 100)}%` }} />
              <div className="bg-amber-300 flex-1" />
            </div>
          </div>
        </div>

        <nav className="flex items-center gap-0 mt-4 -mx-6 px-6 border-t border-slate-100">
          {navLinks.map(link => {
            const isActive = link.id === activeNav;
            const handleClick = () => {
              if (link.href) window.open(link.href, "_blank");
              else onNavChange(link.id);
            };
            return (
              <button
                key={link.id}
                onClick={handleClick}
                className={`flex items-center gap-1.5 text-sm px-4 py-2.5 border-b-2 font-medium transition-all whitespace-nowrap ${
                  isActive
                    ? "border-indigo-600 text-indigo-600"
                    : "border-transparent text-slate-500 hover:text-slate-800 hover:border-slate-300"
                }`}
              >
                <span className="text-base leading-none">{link.icon}</span>
                {link.label}
                {link.href && <span className="text-[10px] text-slate-300 ml-0.5">↗</span>}
              </button>
            );
          })}
        </nav>
      </div>
    </div>
  );
};

window.SpecComponents = window.SpecComponents || {};
window.SpecComponents.SpecHeader = SpecHeader;
