'use client';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import { useEffect, useState } from "react";
import { useAuth } from '@payloadcms/ui';
import Link from 'next/link';
import './RecentlyVisitedPlugin.css';
var DEFAULT_BREADCRUMB_CLASS_NAME = '.step-nav__last';
var LOCAL_STORAGE_KEY = 'payload-plugin-recently-visited-links';
var RecentlyVisited = function (_a) {
    var _b, _c;
    var pluginOptions = _a.pluginOptions;
    var user = useAuth().user;
    var _d = useState([]), lastLinks = _d[0], setLastLinks = _d[1];
    var _e = useState(true), isOpen = _e[0], setIsOpen = _e[1];
    var recentlyVisitedPlugin = user === null || user === void 0 ? void 0 : user.recentlyVisitedPlugin;
    var isRecentlyVisitedEnabled = (_b = recentlyVisitedPlugin === null || recentlyVisitedPlugin === void 0 ? void 0 : recentlyVisitedPlugin.enabled) !== null && _b !== void 0 ? _b : true;
    var maxVisitedLinks = (_c = recentlyVisitedPlugin === null || recentlyVisitedPlugin === void 0 ? void 0 : recentlyVisitedPlugin.amount) !== null && _c !== void 0 ? _c : 4;
    var toggleDropdown = function () {
        setIsOpen(!isOpen);
    };
    var getBreadcrumbLastText = function () { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            return [2 /*return*/, new Promise(function (resolve) {
                    var breadcrumbLastElement = document.querySelector((pluginOptions === null || pluginOptions === void 0 ? void 0 : pluginOptions.breadcrumbClass)
                        ? pluginOptions === null || pluginOptions === void 0 ? void 0 : pluginOptions.breadcrumbClass
                        : DEFAULT_BREADCRUMB_CLASS_NAME);
                    if (!breadcrumbLastElement) {
                        breadcrumbLastElement = document.querySelector('.app-header__step-nav');
                    }
                    resolve(breadcrumbLastElement ? breadcrumbLastElement.textContent : null);
                })];
        });
    }); };
    var updateLastLinks = function (url) { return __awaiter(void 0, void 0, void 0, function () {
        var breadcrumbText, pathToSave, linkObject, savedLinks, updatedLinks;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!isRecentlyVisitedEnabled)
                        return [2 /*return*/];
                    return [4 /*yield*/, getBreadcrumbLastText()];
                case 1:
                    breadcrumbText = _a.sent();
                    pathToSave = new URL(url).pathname;
                    linkObject = { path: pathToSave, textContent: breadcrumbText || 'Link' };
                    savedLinks = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY) || '[]');
                    updatedLinks = __spreadArray([
                        linkObject
                    ], savedLinks.filter(function (link) { return link.path !== pathToSave; }), true).slice(0, maxVisitedLinks);
                    if (JSON.stringify(updatedLinks) !== JSON.stringify(savedLinks)) {
                        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(updatedLinks));
                    }
                    setLastLinks(updatedLinks);
                    return [2 /*return*/];
            }
        });
    }); };
    useEffect(function observeBreadcrumb() {
        var _this = this;
        if (!isRecentlyVisitedEnabled)
            return;
        var savedLinks = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY) || '[]');
        setLastLinks(savedLinks);
        var observer = new MutationObserver(function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, updateLastLinks(window.location.href)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); });
        var breadcrumbContainer = document.querySelector('.app-header__step-nav-wrapper');
        if (breadcrumbContainer) {
            observer.observe(breadcrumbContainer, {
                childList: true,
                subtree: true,
                characterData: true,
            });
        }
        else {
            console.error('[PayloadPluginRecentlyVisited]: Breadcrumb container (`.app-header__step-nav-wrapper`) not found.');
        }
        return function () {
            observer.disconnect();
        };
    }, [isRecentlyVisitedEnabled]);
    if (!isRecentlyVisitedEnabled)
        return null;
    return (<div className="nav-group RecentlyVisitedPluginNav nav-group--collapsed" id="nav-group-RecentlyVisitedPlugin">
      <button onClick={toggleDropdown} className={"nav-group__toggle ".concat(isOpen ? 'nav-group__toggle--open' : 'nav-group__toggle--collapsed')} type="button">
        <div className="nav-group__label">Recently visited ({maxVisitedLinks})</div>
        <div className="nav-group__indicator">
          <svg style={{ transform: isOpen ? 'rotate(180deg)' : '' }} className="icon icon--chevron nav-group__indicator" viewBox="0 0 9 7" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
            <path className="stroke" d="M1.42871 1.5332L4.42707 4.96177L7.42543 1.5332"></path>
          </svg>
        </div>
      </button>

      {isOpen && (<div className="nav-group__content">
          {lastLinks.map(function (link, index) { return (<Link href={link.path} className="nav__link" key={index} aria-label={link.textContent}>
              <span title={link.textContent}>{link.textContent}</span>
            </Link>); })}
        </div>)}
    </div>);
};
export default RecentlyVisited;
//# sourceMappingURL=RecentlyVisited.jsx.map