const template = html`
  <div
    id="sidebar"
    class="task-beta ng-scope d-none"
    ng-controller="SidebarCtrl"
  >
    <div id="sidebar-user">
      <div class="pull-left">
        <img
          :src="avatar"
          alt="Profile Photo"
        />
      </div>
      <div class="user_info">
        <h4 v-if="loading">Loading...</h4>
        <h4 v-else-if="me.name">{{me.name}}</h4>
        <h4 v-else-if="me.first_name && me.last_name">{{me.first_name}} {{me.last_name}}</h4>
        <h4 v-else-if="me.username">{{me.username}}</h4>
        <h4 v-else>User</h4>
        <clocking></clocking>
        <div class="user_options" @click="showEditProfile">
          <h5>Edit Profile</h5>
        </div>
        <div class="user_options" onclick="window.location = '/hr'">
          <h5>Timesheet</h5>
        </div>
        <div class="user_options" onclick="window.location = '/logout'">
          <h5>Logout</h5>
        </div>        
      </div>
    </div>

    <div>
      <div class="channels_header">Notifications    <div onclick="window.location = '/notifications'" class="notifications-btn"><h5>All Notifications</h5></div></div>
      <notifications></notifications>

    </div>
    <div id="tech-docs">
		<div class="channels_header">Useful Documents</div>
		<a href="https://seraph.computerassistance.uk/docs/general-repairs-guidelines"><i class="fa fa-file"></i> &nbsp;General Repair Guidelines</a> <br>
		<a href="https://seraph.computerassistance.uk/docs/new-machine-checklist"><i class="fa fa-file"></i> &nbsp;New Machine Checklist</a> <br>
		<a href="https://seraph.computerassistance.uk/docs/technician-pricing-and-warranty"><i class="fa fa-file"></i> &nbsp;Technician Pricing and Warranty</a>
		<a href="https://seraph.computerassistance.uk/files/QA_Repairs.pdf" target="_blank" style="display: block;"><i class="fa fa-file"></i> &nbsp;QA Repairs</a>
		<a href="https://seraph.computerassistance.uk/files/QA_New_Builds.pdf" target="_blank" style="display: block;"><i class="fa fa-file"></i> &nbsp;QA New Builds</a>
		<a href="https://seraph.computerassistance.uk/files/Antivirus-Anti malware Guide.pdf" target="_blank" style="display: block;"><i class="fa fa-file"></i> &nbsp;Antivirus and Anti malware Guide</a>
		<a href="https://seraph.computerassistance.uk/files/Laptop Screen Replacement, Diagnosis and Repair.pdf" target="_blank" style="display: block;"><i class="fa fa-file"></i> &nbsp;Laptop Screen Replacement  Diagnosis and Repair</a>
		<a href="https://seraph.computerassistance.uk/files/Liquid Damage Repairs.pdf" target="_blank" style="display: block;"><i class="fa fa-file"></i> &nbsp;Liquid Damage Repairs</a>
		<a href="https://seraph.computerassistance.uk/files/Standard Repair Operating Procedure.pdf" target="_blank" style="display: block;"><i class="fa fa-file"></i> &nbsp;Standard Repair Operating Procedure</a>
		<a href="https://seraph.computerassistance.uk/files/Windows Reinstall Procedure.pdf" target="_blank" style="display: block;"><i class="fa fa-file"></i> &nbsp;Windows Reinstall Procedure</a>
	</div>

    <div id="sidebar-tabs">
    <div class="sidebar-tab" data-unique='1' data-placement="top" data-container="#sidebar" onclick="window.open('/changelog', '_blank')" style="cursor: pointer;">
			<i class="fa fa-code-fork" style="color: white;"></i>
		</div>      
       <qucktask ></qucktask>
    </div>
  </div>
`;

import clocking from "../generic/clocking.js?v=20251013";
import notifications from "../generic/notifications.js?v=20251013";
import qucktask from "../generic/qucktask.js?v=20251013";
import api from "../../api.js?v=20251013";
import state from "../../state/main.js?v=20251013";

export default {
  data: function () {
    return {
      me: {},
      loading: true,
      // toggle:false,
    };
  },
  components: {
    clocking,
    notifications,
    qucktask
  },
  mounted() {
    this.loadMe()
  },
  computed: {
    emailhash() {
      if (!this.me.email) {
        return ''
      }
      return this.simpleHash(this.me.email.toLowerCase())
    },
    avatar() {
      // Use profile_photo_url from API response if available
      if (this.me.profile_photo_url) {
        return this.me.profile_photo_url
      }

      // Fall back to Gravatar
      if (!this.me.name) {
        return 'https://www.gravatar.com/avatar/?d=mp'
      }
      const name = this.me.name.split(' ').join('%2B')
      return `https://www.gravatar.com/avatar/${this.emailhash}?d=https%3A%2F%2Fui-avatars.com%2Fapi%2F/${name}/128?r=pg`
    }
  },
  methods: {
    showEditProfile() {
      // Check if AngularJS is available and trigger the settings modal
      const scope = angular.element(document.getElementById('sidebar')).scope();
      if (scope && scope.showSettings) {
        // Set the user data on the AngularJS scope before opening modal
        scope.user = this.me;
        scope.$apply(() => {
          scope.showSettings();
        });
      } else {
        console.error('AngularJS scope or showSettings method not found');
      }
    },
    async loadMe() {
      try {
        console.log('🔄 Sidebar: Loading user data...');

        // Check if state management is available
        if (state && state.sub && state.set) {
          state.sub("me", value => {
            console.log('📡 Sidebar: Received user data from state:', value);
            this.me = value || {};
          });
        }

        // Load user data from API
        const data = await api.get.me();
        console.log('✅ Sidebar: User data loaded from API:', data);

        this.me = data || {};
        this.loading = false;

        // Update state if available
        if (state && state.set) {
          state.set("me", data);
        }
      } catch (error) {
        console.error('❌ Sidebar: Failed to load user data:', error);
        this.me = {};
        this.loading = false;
      }
    },
    // Simple hash function to replace MD5
    simpleHash(str) {
      let hash = 0;
      if (str.length === 0) return hash.toString(16);
      for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // Convert to 32bit integer
      }
      return Math.abs(hash).toString(16);
    }
  },
  template
};
