/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	// The require scope
/******/ 	var __webpack_require__ = {};
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
/*!*********************************!*\
  !*** ./extension/js/profile.js ***!
  \*********************************/
__webpack_require__.r(__webpack_exports__);
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
// js/profile.js

document.addEventListener('DOMContentLoaded', function () {
  // --- UI ELEMENTS ---
  var trustScoreDisplay = document.getElementById('trust-score-display');
  var creditsDisplay = document.getElementById('credits-display');
  var locationInput = document.getElementById('location-input');
  var interestsInput = document.getElementById('interests-input');
  var bioInput = document.getElementById('bio-input');
  var aboutHeading = document.getElementById('about-heading');
  var saveProfileBtn = document.getElementById('save-profile-btn');

  // <-- NEW BUTTONS ADDED HERE -->
  var closeProfileBtn = document.getElementById('close-profile-btn');
  var unsavedWarning = document.getElementById('unsaved-warning');

  // NEW ANNOTATIONS HISTORY ELEMENTS
  var loadAnnotationsBtn = document.getElementById('load-annotations-btn');
  var annotationsListContainer = document.getElementById('annotations-list-container');
  var annotationsScrollBox = document.getElementById('annotations-scroll-box');
  var copyAnnotationsBtn = document.getElementById('copy-annotations-btn');

  // NEW CAMERA UI ELEMENTS
  var video = document.getElementById('webcam-video');
  var canvas = document.getElementById('webcam-canvas');
  var imageDisplay = document.getElementById('profile-image-display');
  var startCameraBtn = document.getElementById('start-camera-btn');
  var snapPhotoBtn = document.getElementById('snap-photo-btn');
  var cancelCameraBtn = document.getElementById('cancel-camera-btn');

  // --- DIRTY STATE MEMORY ---
  // <-- NEW MEMORY VARIABLES ADDED HERE -->
  // This will store the profile exactly as it loaded from the database
  var originalData = {
    location: '',
    interests: '',
    bio: ''
  };
  var hasNewPhoto = false;

  // --- DIRTY STATE CHECKER FUNCTION ---
  function checkDirtyState() {
    // Check if any text box is different from the original, OR if a new photo was snapped
    var isDirty = locationInput.value !== originalData.location || interestsInput.value !== originalData.interests || bioInput.value !== originalData.bio || hasNewPhoto;
    if (isDirty) {
      // Changes detected! Turn button blue, enable it, and show warning
      saveProfileBtn.disabled = false;
      saveProfileBtn.style.backgroundColor = '#0000AF';
      saveProfileBtn.style.cursor = 'pointer';
      unsavedWarning.style.display = 'block';
      closeProfileBtn.style.backgroundColor = '#6c757d';
    } else {
      // Back to original state! Turn button grey, disable it, and hide warning
      saveProfileBtn.disabled = true;
      saveProfileBtn.style.backgroundColor = '#6c757d';
      saveProfileBtn.style.cursor = 'not-allowed';
      unsavedWarning.style.display = 'none';
      closeProfileBtn.style.backgroundColor = '#0000AF';
    }
  }

  // Attach the checker to listen for typing in the text boxes
  locationInput.addEventListener('input', checkDirtyState);
  interestsInput.addEventListener('input', checkDirtyState);
  bioInput.addEventListener('input', checkDirtyState);
  var currentUserUid = null;
  var mediaStream = null; // Holds the live video feed
  var newAvatarDataUrl = null; // Holds our snapped photo before saving

  // --- 1. GET CURRENT USER & FETCH DATA ---
  chrome.runtime.sendMessage({
    type: 'getAuthStatus',
    target: 'background'
  }, function (authResponse) {
    if (authResponse && authResponse.user) {
      currentUserUid = authResponse.user.uid;
      chrome.runtime.sendMessage({
        type: 'getUserData',
        target: 'background',
        data: {
          uid: currentUserUid
        }
      }, function (response) {
        if (response && response.data) {
          var userData = response.data;
          trustScoreDisplay.textContent = userData.trustScore !== undefined ? userData.trustScore : '10';
          creditsDisplay.textContent = userData.creditsBalance !== undefined ? userData.creditsBalance : '0';
          if (userData.location) {
            locationInput.value = userData.location;
            originalData.location = userData.location;
          }
          if (userData.interests) {
            interestsInput.value = userData.interests;
            originalData.interests = userData.interests;
          }
          if (userData.bio) {
            bioInput.value = userData.bio;
            originalData.bio = userData.bio;
          }
          // <-- ADD THIS LINE: Change the heading if they have a username saved
          if (userData.displayName) aboutHeading.textContent = "About ".concat(userData.displayName);

          // If they already have a profile picture in the database, show it!
          if (userData.photoURL) imageDisplay.src = userData.photoURL;
        } else {
          trustScoreDisplay.textContent = 'Error';
          creditsDisplay.textContent = 'Error';
        }
      });
    } else {
      trustScoreDisplay.textContent = 'N/A';
      creditsDisplay.textContent = 'N/A';
      alert('Please sign in through the Anotato extension popup first.');
    }
  });

  // --- 2. CAMERA LOGIC ---

  // Turn camera on
  startCameraBtn.addEventListener('click', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
    var _t;
    return _regenerator().w(function (_context) {
      while (1) switch (_context.p = _context.n) {
        case 0:
          _context.p = 0;
          _context.n = 1;
          return navigator.mediaDevices.getUserMedia({
            video: true
          });
        case 1:
          mediaStream = _context.v;
          video.srcObject = mediaStream;

          // Swap UI
          video.style.display = 'block';
          imageDisplay.style.display = 'none';
          startCameraBtn.style.display = 'none';
          snapPhotoBtn.style.display = 'inline-block';
          cancelCameraBtn.style.display = 'inline-block';
          _context.n = 3;
          break;
        case 2:
          _context.p = 2;
          _t = _context.v;
          console.error("Camera error:", _t);
          alert('Unable to access camera. Please check your browser site settings and allow camera access.');
        case 3:
          return _context.a(2);
      }
    }, _callee, null, [[0, 2]]);
  })));

  // Snap the photo
  snapPhotoBtn.addEventListener('click', function () {
    var context = canvas.getContext('2d');
    // Draw the current video frame onto the hidden canvas
    context.drawImage(video, 0, 0, canvas.width, canvas.height);

    // Extract the image as a compressed JPEG Data URL
    newAvatarDataUrl = canvas.toDataURL('image/jpeg', 0.8);

    // Show the snapped photo and turn the camera off
    imageDisplay.src = newAvatarDataUrl;
    hasNewPhoto = true;
    checkDirtyState();
    stopCamera();
  });

  // Cancel camera
  cancelCameraBtn.addEventListener('click', function () {
    stopCamera();
  });

  // Helper to shut down the hardware camera light
  function stopCamera() {
    if (mediaStream) {
      mediaStream.getTracks().forEach(function (track) {
        return track.stop();
      });
    }
    video.style.display = 'none';
    imageDisplay.style.display = 'inline-block';
    startCameraBtn.style.display = 'inline-block';
    snapPhotoBtn.style.display = 'none';
    cancelCameraBtn.style.display = 'none';
  }

  // --- 3. SAVE BUTTON HANDLER ---
  saveProfileBtn.addEventListener('click', function () {
    if (!currentUserUid) {
      alert('User ID not found. Please reload the page.');
      return;
    }
    saveProfileBtn.textContent = 'Saving...';
    saveProfileBtn.disabled = true;
    var profileData = {
      uid: currentUserUid,
      location: locationInput.value.trim(),
      interests: interestsInput.value.trim(),
      bio: bioInput.value.trim(),
      // Pass our newly snapped photo to the background!
      newAvatar: newAvatarDataUrl
    };
    chrome.runtime.sendMessage({
      type: 'updateUserProfile',
      target: 'background',
      data: profileData
    }, function (response) {
      if (response && response.success) {
        saveProfileBtn.textContent = 'Saved! ✅';
        saveProfileBtn.style.backgroundColor = '#28a745';

        // <-- ADD THIS BLOCK: Quietly fetch the newly updated score in the background
        chrome.runtime.sendMessage({
          type: 'getUserData',
          target: 'background',
          data: {
            uid: currentUserUid
          }
        }, function (res) {
          if (res && res.data && res.data.trustScore !== undefined) {
            trustScoreDisplay.textContent = res.data.trustScore;
          }
        });
        setTimeout(function () {
          saveProfileBtn.textContent = 'Save Profile';

          // Update the memory NOW, after the 2-second success message
          originalData = {
            location: locationInput.value,
            interests: interestsInput.value,
            bio: bioInput.value
          };
          hasNewPhoto = false;

          // Let the checker handle the colors and disabling!
          checkDirtyState();
        }, 2000);
      } else {
        alert('Error saving profile: ' + (response ? response.error : 'Unknown error'));
        saveProfileBtn.textContent = 'Save Profile';
        saveProfileBtn.disabled = false;
      }
    });
  }); // <-- This closes your Save Button listener

  // --- STEP 4: THE CLOSE BUTTON ACTION ---
  closeProfileBtn.addEventListener('click', function () {
    window.close();
  });

  // --- 5. LOAD ANNOTATIONS HISTORY ---
  loadAnnotationsBtn.addEventListener('click', function () {
    if (!currentUserUid) return;

    // 1. Confirm the transaction with the user
    var confirmed = confirm("This will deduct 1 credit to load your entire annotation history. Proceed?");
    if (!confirmed) return;

    // 2. Set loading state
    loadAnnotationsBtn.textContent = 'Loading History...';
    loadAnnotationsBtn.disabled = true;
    loadAnnotationsBtn.style.backgroundColor = '#6c757d';

    // 3. Ask the background script to fetch the data and handle the payment
    chrome.runtime.sendMessage({
      type: 'fetchUserHistory',
      target: 'background',
      data: {
        uid: currentUserUid
      }
    }, function (response) {
      if (response && response.success) {
        // Instantly update the credit display on the UI
        var currentCredits = parseInt(creditsDisplay.textContent) || 0;
        creditsDisplay.textContent = Math.max(0, currentCredits - 1);

        // Clear out any old data
        annotationsScrollBox.innerHTML = '';
        if (response.annotations.length === 0) {
          annotationsScrollBox.innerHTML = '<p style="color: #666; text-align: center;">You have no annotations yet.</p>';
        } else {
          // Loop through the data and build the 3-line UI
          response.annotations.forEach(function (ann) {
            var statusColor = ann.isDeleted ? '#dc3545' : '#28a745';
            var statusText = ann.isDeleted ? 'DELETED' : 'ACTIVE';
            var dateStr = "Unknown Date";
            if (ann.createdAt) {
              var dateObj = ann.createdAt.seconds ? new Date(ann.createdAt.seconds * 1000) : new Date(ann.createdAt);
              dateStr = dateObj.toLocaleDateString();
            }

            // 1. STRIP BASE64 IMAGES AND HTML: Force text-only content
            var tempDiv = document.createElement('div');
            tempDiv.innerHTML = ann.anchorText;
            var cleanAnchor = tempDiv.textContent || tempDiv.innerText || "";
            tempDiv.innerHTML = ann.annotationText;
            var cleanNote = tempDiv.textContent || tempDiv.innerText || "";

            // THIS IS THE LINE THAT CRASHED IT (Now there is only one!)
            var item = document.createElement('div');
            var isRestored = ann.url === "Restored URL";

            // 2. TIGHT SPACING & BLACK LINE
            item.style.borderBottom = '1px solid black';
            item.style.paddingBottom = '8px';
            item.style.marginBottom = '8px';
            item.innerHTML = "\n                            <div style=\"display: flex; justify-content: space-between; align-items: center; margin-bottom: 2px; width: 100%;\">\n                                <div style=\"font-size: 12px; color: #888; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; flex-grow: 1; min-width: 0; padding-right: 10px;\">\n                                    <strong>".concat(dateStr, "</strong> | <span style=\"color: ").concat(statusColor, "; font-weight: bold; margin-right: 5px;\">").concat(statusText, "</span> \n                                    <span style=\"color: #0000AF; font-weight: bold;\">").concat(ann.url, "</span>\n                                </div>\n                                ").concat(isRestored ? '' : "<button class=\"open-url-btn\" style=\"background-color: #0000AF; color: white; border: none; padding: 4px 0; border-radius: 4px; cursor: pointer; font-size: 12px; font-weight: bold; flex-shrink: 0; width: 60px; min-width: 60px; text-align: center;\">Open</button>", "\n                            </div>\n                            \n                            <div style=\"font-size: 14px; color: #333; font-style: italic; background: #eee; padding: 2px 4px; margin-bottom: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\">\"").concat(cleanAnchor, "\"</div>\n                            \n                            <div style=\"font-size: 14px; color: #555; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 2px;\">").concat(cleanNote, "</div>\n                        ");
            if (!isRestored) {
              var btn = item.querySelector('.open-url-btn');
              btn.addEventListener('click', function () {
                window.open(ann.url, '_blank');
              });
            }
            annotationsScrollBox.appendChild(item);
          });
        }

        // Hide the load button and reveal the scrollable box
        loadAnnotationsBtn.style.display = 'none';
        annotationsListContainer.style.display = 'block';
      } else {
        alert('Error loading history: ' + (response ? response.error : 'Unknown error'));
        loadAnnotationsBtn.textContent = 'Show all my annotations (Costs 1 credit)';
        loadAnnotationsBtn.disabled = false;
        loadAnnotationsBtn.style.backgroundColor = '#0000AF';
      }
    });
  });

  // --- 6. COPY LIST TO CLIPBOARD ---
  copyAnnotationsBtn.addEventListener('click', function () {
    var textToCopy = "My Anotato History:\n\n";

    // Grab all the individual annotation divs we just created
    var items = annotationsScrollBox.querySelectorAll('div[style*="border-bottom"]');
    items.forEach(function (item) {
      // innerText automatically strips the HTML tags and just grabs the readable text
      textToCopy += item.innerText + "\n\n---\n\n";
    });
    navigator.clipboard.writeText(textToCopy).then(function () {
      var originalText = copyAnnotationsBtn.textContent;
      copyAnnotationsBtn.textContent = 'Copied!';
      copyAnnotationsBtn.style.backgroundColor = '#28a745'; // Turn green

      setTimeout(function () {
        copyAnnotationsBtn.textContent = originalText;
        copyAnnotationsBtn.style.backgroundColor = '#6c757d'; // Turn back to grey
      }, 2000);
    });
  });
}); // <-- This is the final closing bracket for the whole page
/******/ })()
;
//# sourceMappingURL=profile.js.map