/* =============================================================
   Lauritz Knudsen — AID Partner Portal
   File: assets/js/common.js
   Shared helpers used by every page:
   sidebar toggle, toast, session, demo data store, form validation.
   ============================================================= */

/* ---------- APP CONFIG (change links here only) ---------- */
var APP_NAME       = "Designer Club";
var PLAY_LINK      = "https://play.google.com/store/apps/details?id=com.lnt.architect&pcampaignid=web_share";
var APP_STORE_LINK = "https://apps.apple.com/in/app/designer-club/id6782594111";

/* ---------- SHORTHAND ---------- */
function $(sel, root){ return (root || document).querySelector(sel); }
function $$(sel, root){ return Array.prototype.slice.call((root || document).querySelectorAll(sel)); }

/* ---------- TOAST ---------- */
function toast(msg){
  var t = $("#toast");
  if(!t){
    t = document.createElement("div");
    t.id = "toast";
    t.className = "toast";
    t.setAttribute("role", "status");
    document.body.appendChild(t);
  }
  t.textContent = msg;
  t.classList.add("show");
  clearTimeout(t._timer);
  t._timer = setTimeout(function(){ t.classList.remove("show"); }, 2800);
}

/* =============================================================
   SIDEBAR TOGGLE
   Works on every inner page. On desktop the sidebar is always
   visible; below 900px it slides in as a drawer with a backdrop.
   ============================================================= */
function initSidebar(){
  var sidebar  = $("#sidebar");
  var backdrop = $("#sidebarBackdrop");
  if(!sidebar) return;

  function open(){
    sidebar.classList.add("open");
    if(backdrop) backdrop.classList.add("show");
    document.body.classList.add("no-scroll");
    sidebar.setAttribute("aria-hidden", "false");
  }
  function close(){
    sidebar.classList.remove("open");
    if(backdrop) backdrop.classList.remove("show");
    document.body.classList.remove("no-scroll");
    sidebar.setAttribute("aria-hidden", "true");
  }
  function toggle(){
    sidebar.classList.contains("open") ? close() : open();
  }

  var burger = $("#hamburger");
  var closeBtn = $("#sidebarClose");
  if(burger)   burger.addEventListener("click", toggle);
  if(closeBtn) closeBtn.addEventListener("click", close);
  if(backdrop) backdrop.addEventListener("click", close);

  /* close the drawer after tapping a nav link on mobile */
  $$(".sidebar .nav-item").forEach(function(item){
    item.addEventListener("click", function(){
      if(window.innerWidth <= 900) close();
    });
  });

  /* Escape closes the drawer */
  document.addEventListener("keydown", function(e){
    if(e.key === "Escape" && sidebar.classList.contains("open")) close();
  });

  /* reset state when resizing back up to desktop */
  window.addEventListener("resize", function(){
    if(window.innerWidth > 900) close();
  });

  window.LKSidebar = { open: open, close: close, toggle: toggle };
}

/* =============================================================
   SESSION + DEMO DATA STORE
   ---------------------------------------------------------------
   DEVELOPER NOTE (PHP):
   This front-end demo keeps the logged-in user and the architect
   list in sessionStorage so the pages can talk to each other
   without a backend. In production replace every function below
   with real server calls:

     Store.getUser()        -> PHP session ($_SESSION['aid_email'])
     Store.getArchitects()  -> get_architects.php
     Store.addArchitect()   -> register_architect.php
     Store.updateArchitect()-> update_architect.php
     Store.clear()          -> logout.php
   ============================================================= */
var Store = {
  KEY_USER: "lk_aid_user",
  KEY_LIST: "lk_architects",

  getUser: function(){
    try { return JSON.parse(sessionStorage.getItem(this.KEY_USER)) || null; }
    catch(e){ return null; }
  },
  setUser: function(user){
    sessionStorage.setItem(this.KEY_USER, JSON.stringify(user));
  },
  getArchitects: function(){
    try { return JSON.parse(sessionStorage.getItem(this.KEY_LIST)) || []; }
    catch(e){ return []; }
  },
  saveArchitects: function(list){
    sessionStorage.setItem(this.KEY_LIST, JSON.stringify(list));
  },
  addArchitect: function(architect){
    var list = this.getArchitects();
    list.unshift(architect);
    this.saveArchitects(list);
    return list;
  },
  updateArchitect: function(index, data){
    var list = this.getArchitects();
    if(list[index]){
      for(var k in data){ list[index][k] = data[k]; }
      this.saveArchitects(list);
    }
    return list;
  },
  getArchitect: function(index){
    return this.getArchitects()[index] || null;
  },
  setLastInvite: function(index){
    sessionStorage.setItem("lk_last_invite", String(index));
  },
  getLastInvite: function(){
    var i = sessionStorage.getItem("lk_last_invite");
    return i === null ? -1 : parseInt(i, 10);
  },
  clear: function(){
    sessionStorage.removeItem(this.KEY_USER);
    sessionStorage.removeItem(this.KEY_LIST);
    sessionStorage.removeItem("lk_last_invite");
  }
};

/* =============================================================
   AUTH GUARD + SIDEBAR USER CHIP
   Call requireLogin() at the top of every inner page.
   DEVELOPER: replace with a PHP session check at the top of the file.
   ============================================================= */
function requireLogin(){
  var user = Store.getUser();
  if(!user){
    window.location.href = "index.html";
    return null;
  }
  var nameEl = $("#uName"), idEl = $("#uId"), avEl = $("#uAvatar");
  if(nameEl) nameEl.textContent = user.name;
  if(idEl)   idEl.textContent   = user.email;
  if(avEl)   avEl.textContent   = user.name.charAt(0).toUpperCase();
  return user;
}

function logout(){
  /* DEVELOPER: call logout.php to destroy the PHP session. */
  Store.clear();
  window.location.href = "index.html";
}

/* =============================================================
   STATE / CITY DATA
   DEVELOPER: load these from the database via get_cities.php
   if the client wants a full master list.
   ============================================================= */
var STATE_CITY = {
  "Maharashtra":    ["Mumbai","Navi Mumbai","Thane","Pune","Nagpur","Nashik","Aurangabad","Other"],
  "Gujarat":        ["Ahmedabad","Surat","Vadodara","Rajkot","Gandhinagar","Other"],
  "Delhi":          ["New Delhi","Dwarka","Rohini","Saket","Other"],
  "Karnataka":      ["Bengaluru","Mysuru","Mangaluru","Hubballi","Other"],
  "Tamil Nadu":     ["Chennai","Coimbatore","Madurai","Tiruchirappalli","Other"],
  "Telangana":      ["Hyderabad","Warangal","Nizamabad","Other"],
  "Uttar Pradesh":  ["Lucknow","Noida","Ghaziabad","Kanpur","Varanasi","Other"],
  "West Bengal":    ["Kolkata","Howrah","Durgapur","Siliguri","Other"],
  "Rajasthan":      ["Jaipur","Udaipur","Jodhpur","Kota","Other"],
  "Madhya Pradesh": ["Indore","Bhopal","Gwalior","Jabalpur","Other"],
  "Kerala":         ["Kochi","Thiruvananthapuram","Kozhikode","Other"],
  "Punjab":         ["Ludhiana","Amritsar","Chandigarh","Other"],
  "Other":          ["Other"]
};

function populateStates(selectEl){
  if(!selectEl) return;
  var html = '<option value="">Select state</option>';
  for(var state in STATE_CITY){ html += '<option>' + state + '</option>'; }
  selectEl.innerHTML = html;
}

function populateCities(stateEl, cityEl, selectedCity){
  if(!stateEl || !cityEl) return;
  var cities = STATE_CITY[stateEl.value] || [];
  if(!stateEl.value){
    cityEl.innerHTML = '<option value="">Select state first</option>';
    return;
  }
  var html = '<option value="">Select city</option>';
  cities.forEach(function(c){ html += '<option>' + c + '</option>'; });
  cityEl.innerHTML = html;
  if(selectedCity) cityEl.value = selectedCity;
}

/* =============================================================
   VALIDATION HELPERS
   ============================================================= */
var Validate = {
  mobile: function(v){ return /^[6-9]\d{9}$/.test(v); },
  email:  function(v){ return /^\S+@\S+\.\S+$/.test(v); },
  pin:    function(v){ return v === "" || /^\d{6}$/.test(v); },
  filled: function(v){ return v.trim().length > 0; },

  /* mark a .field wrapper as valid / invalid */
  mark: function(fieldId, isValid){
    var el = $("#" + fieldId);
    if(el) el.classList.toggle("invalid", !isValid);
    return isValid;
  },
  reset: function(formSelector){
    $$(formSelector + " .field").forEach(function(f){ f.classList.remove("invalid"); });
  }
};

/* only digits, used on mobile + pincode inputs */
function digitsOnly(input){
  if(!input) return;
  input.addEventListener("input", function(){
    this.value = this.value.replace(/\D/g, "");
  });
}

/* =============================================================
   SHARE MESSAGE (English — used by WhatsApp / SMS / Email)
   ============================================================= */
function buildInviteText(architect, aidEmail){
  return "Hello " + architect.name + ",\n\n" +
    "You have been registered on the " + APP_NAME + " app by Lauritz Knudsen Electrical & Automation.\n\n" +
    "Download the app:\n" +
    "Android (Play Store): " + PLAY_LINK + "\n" +
    "iPhone (App Store): " + APP_STORE_LINK + "\n\n" +
    "Your login details:\n" +
    "Login ID: " + architect.loginId + "\n" +
    "Temporary Password: " + architect.pass + "\n\n" +
    "Please set a new password on your first login.\n\n" +
    "Regards,\n" + aidEmail + "\n" +
    "Lauritz Knudsen Electrical & Automation";
}

/* generate a temporary password
   DEVELOPER: the real password must be generated on the server. */
function generatePassword(){
  var chars = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
  var p = "LK@";
  for(var i = 0; i < 5; i++){ p += chars.charAt(Math.floor(Math.random() * chars.length)); }
  return p;
}

/* copy text to clipboard with fallback for older browsers */
function copyText(text, message){
  if(navigator.clipboard && window.isSecureContext){
    navigator.clipboard.writeText(text).then(function(){ toast(message || "Copied"); });
  } else {
    var ta = document.createElement("textarea");
    ta.value = text;
    ta.style.position = "fixed";
    ta.style.opacity = "0";
    document.body.appendChild(ta);
    ta.select();
    try { document.execCommand("copy"); toast(message || "Copied"); }
    catch(e){ toast("Copy failed — please select the text manually"); }
    document.body.removeChild(ta);
  }
}

function escapeHtml(str){
  return String(str == null ? "" : str)
    .replace(/&/g, "&amp;").replace(/</g, "&lt;")
    .replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

/* boot the sidebar on every page that has one */
document.addEventListener("DOMContentLoaded", initSidebar);
