
<?php
// PHP helpers
$p        = $profile;
$photoUrl = ! empty($p['profile_photo'])
    ? base_url('uploads/' . $p['profile_photo'])
    : base_url('assets/images/avatar_placeholder.svg');
$logoUrl  = ! empty($p['company_logo'])
    ? base_url('uploads/' . $p['company_logo'])
    : '';
$profileUrl = site_url('profile/' . $p['slug']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Edit Profile — <?= esc($profile['name']) ?></title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/cropperjs@1.5.13/dist/cropper.min.css" rel="stylesheet">
  <style>
    :root {
      --primary: #f9811e;
      --secondary: #00a854;
      --bg: #f4f2ee;
      --card-bg: #ffffff;
      --text-dark: #191919;
      --text-muted: #666666;
      --border-light: #e8e8e8;
    }
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: 'DM Sans', sans-serif; background: var(--bg); color: var(--text-dark); overflow-x: hidden; }
    .app-shell { width: 100%; max-width: 480px; margin: 0 auto; background: var(--bg); padding-bottom: 60px; }

     /* === BANNER & NAVIGATION === */
    .cover-banner {
      width: 100%;
      height: 100px;
     /* background: linear-gradient(135deg, #1a3a5c 0%, #0d2137 60%, #0a1929 100%);*/
      position: relative;
      overflow: hidden;
      background: url(<?= esc($logoUrl) ?>);
      background-position: center;
      background-size: contain;
      background-repeat: no-repeat;
    }

    .cover-banner::before {
      content: '';
      position: absolute;
      top: -40px;
      right: -40px;
      width: 180px;
      height: 180px;
      background: radial-gradient(circle, rgba(249, 129, 30, 0.15) 0%, transparent 70%);
      border-radius: 50%;
    }

    .cover-banner::after {
      content: '';
      position: absolute;
      bottom: -30px;
      left: 30%;
      width: 220px;
      height: 220px;
      background: radial-gradient(circle, rgba(0, 168, 84, 0.1) 0%, transparent 70%);
      border-radius: 50%;
    }

    .banner-menu {
      position: absolute;
      top: 14px;
      right: 16px;
      z-index: 50;
      /* display: none !important; */
    }

    .menu-btn {
      width: 44px;
      height: 44px;
      background: rgba(255, 255, 255, 0.12);
      backdrop-filter: blur(8px);
      border: none;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.3s ease;
      color: rgba(255, 255, 255, 0.9);
      font-size: 20px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .menu-btn:hover {
      background: rgba(255, 255, 255, 0.2);
      transform: scale(1.05);
    }

    .menu-btn:active {
      transform: scale(0.98);
    }

    /* === DRAWER MENU === */
    .menu-overlay {
      position: fixed; inset: 0;
      background: rgba(0,0,0,0); backdrop-filter: blur(0);
      z-index: 99; opacity: 0; pointer-events: none;
      transition: all .3s;
    }
    .menu-overlay.active { background: rgba(0,0,0,.5); backdrop-filter: blur(4px); opacity: 1; pointer-events: auto; }
    .menu-drawer {
      position: fixed; top: 0; right: 0; width: 100%; max-width: 300px; height: 100%;
      background: var(--card-bg); box-shadow: -4px 0 24px rgba(0,0,0,.12);
      z-index: 100; transform: translateX(100%);
      transition: transform .35s cubic-bezier(.4,0,.2,1);
      display: flex; flex-direction: column; overflow-y: auto;
    }
    .menu-drawer.active { transform: translateX(0); }
    .menu-drawer-header {
      padding: 20px; border-bottom: 1px solid var(--border-light);
      display: flex; justify-content: space-between; align-items: center;
    }
    .menu-close-btn {
      width: 36px; height: 36px; background: transparent; border: none;
      border-radius: 8px; display: flex; align-items: center; justify-content: center;
      cursor: pointer; color: var(--text-muted); font-size: 20px;
    }
    .menu-items { flex: 1; padding: 8px 0; list-style: none; }
    .menu-item-link {
      display: flex; align-items: center; gap: 16px; padding: 14px 20px;
      text-decoration: none; color: var(--text-dark);
      border-left: 3px solid transparent; transition: all .2s;
    }
    .menu-item-link:hover { background: #fafafa; border-left-color: var(--primary); }
    .menu-item-icon {
      width: 38px; height: 38px;
      background: linear-gradient(135deg, rgba(249,129,30,.1), rgba(0,168,84,.1));
      border-radius: 10px; display: flex; align-items: center; justify-content: center;
      font-size: 17px; color: var(--primary); flex-shrink: 0;
    }
    .menu-item-label { font-size: 14px; font-weight: 600; }
    .menu-item-subtitle { font-size: 11px; color: var(--text-muted); }
    .menu-divider { height: 1px; background: var(--border-light); margin: 6px 0; }

    /* === PROFILE CARD === */
    .profile-main-card {
      background: var(--card-bg); margin: 0 0 14px; padding: 20px;
      border-radius: 16px; box-shadow: 0 1px 4px rgba(0,0,0,.06);
    }
    .hero-left { display: flex; flex-direction: column; align-items: center; gap: 5px; }

    /* === AVATAR FLIP CARD === */
    .avatar-flip-wrap {
      width: 128px; height: 128px;
      perspective: 600px; cursor: pointer;
      position: relative;
    }
    .avatar-flip-inner {
      width: 100%; height: 100%;
      position: relative;
      transition: transform .55s cubic-bezier(.4,0,.2,1);
      transform-style: preserve-3d;
    }
	
	
	 /* === PROFILE AVATAR === */
    .profile-avatar-wrap {
      position: relative;
      padding: 0 20px;
      z-index: 10;
      perspective: 1000px;
    }

    .profile-avatar {
      width: 250px;
      height: 250px;
      position: relative;
      cursor: pointer;
      transform-style: preserve-3d;
      transition: transform 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    }

    .profile-avatar.flipped {
      transform: rotateY(180deg);
    }

    .profile-avatar-front,
    .profile-avatar-back {
      width: 100%;
      height: 100%;
      position: absolute;
      backface-visibility: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      border: 4px solid var(--primary);
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
      overflow: hidden;
    }

    /* .profile-avatar-front {
      background: linear-gradient(135deg, var(--primary), #e06800);
    } */

    .profile-avatar-back {
      background: #f5f5f5;
      transform: rotateY(180deg);
    }

    .profile-avatar .initials {
      font-size: 36px;
      font-weight: 700;
      color: #fff;
      letter-spacing: 1px;
      user-select: none;
    }
    /* hover OR JS-toggled flip */
    .avatar-flip-wrap:hover .avatar-flip-inner,
    .avatar-flip-wrap.flipping .avatar-flip-inner {
      transform: rotateY(180deg);
    }
    .avatar-flip-front, .avatar-flip-back {
      position: absolute; width: 100%; height: 100%;
      backface-visibility: hidden; border-radius: 50%;
      border: 4px solid var(--primary);
      box-shadow: 0 4px 18px rgba(0,0,0,.14);
      overflow: hidden;
    }
    .avatar-flip-front { background: #eee; }
    .avatar-flip-back {
      transform: rotateY(180deg);
      background: linear-gradient(135deg, var(--primary), var(--secondary));
      display: flex; flex-direction: column;
      align-items: center; justify-content: center;
      gap: 5px; color: #fff;
    }
    .avatar-flip-back i   { font-size: 30px; }
    .avatar-flip-back span { font-size: 11px; font-weight: 700; text-align: center; line-height: 1.2; letter-spacing: .3px; }
    /* uploading spinner state */
    .avatar-flip-wrap.uploading .avatar-flip-inner { transform: rotateY(180deg); }
    .avatar-flip-wrap.uploading .avatar-flip-back { background: linear-gradient(135deg,#888,#555); }
    /* small "uploading…" label */
    .avatar-upload-status {
      font-size: 10px; font-weight: 700; color: var(--primary);
      text-align: center; margin-top: 5px; min-height: 14px;
    }

    .profile-name { font-size: 24px; font-weight: 700; text-align: center; }
    .profile-designation { font-size: 16px; font-weight: 500; color: var(--text-dark); opacity: .8; text-align: center; }
    .profile-company { font-size: 15px; color: var(--text-muted); display: flex; align-items: center; gap: 5px; justify-content: center; }
    .profile-company i { color: var(--secondary); font-size: 12px; }

    /* === SECTION CARDS === */
    .section-card {
      background: var(--card-bg); margin: 0 0 14px;
      border-radius: 16px; padding: 20px;
      box-shadow: 0 1px 4px rgba(0,0,0,.06);
    }
    .section-header {
      display: flex; align-items: flex-start; justify-content: space-between;
      margin-bottom: 14px;
    }
    .section-title {
      font-size: 18px; font-weight: 700;
      display: flex; align-items: center; gap: 8px;
    }
    .section-title i { color: var(--primary); }
    .edit-btn {
      width: 32px; height: 32px; background: var(--secondary);
      border: none; border-radius: 8px;
      display: flex; align-items: center; justify-content: center;
      cursor: pointer; color: #fff; font-size: 13px;
      transition: all .2s; flex-shrink: 0;
    }
    .edit-btn:hover { opacity: .85; transform: scale(1.05); }

    /* About */
    .about-text {
      font-size: 15px; line-height: 1.65; color: var(--text-muted);
      display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical;
      overflow: hidden; transition: all .3s;
    }
    .about-text.expanded { display: block; -webkit-line-clamp: unset; overflow: visible; }
    .read-more-btn {
      background: none; border: none; padding: 0;
      color: var(--primary); font-weight: 600; font-size: 14px;
      cursor: pointer; font-family: inherit; margin-top: 4px;
    }

    /* Contact rows */
    .contact-row {
      display: flex; align-items: center; gap: 12px;
      padding: 11px 0; border-bottom: 1px solid #f0f0f0;
      text-decoration: none; color: var(--text-dark);
    }
    .contact-row:last-child { border-bottom: none; }
    .contact-icon {
      width: 38px; height: 38px; background: rgba(0,168,84,.08);
      border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;
    }
    .contact-icon i { font-size: 17px; color: var(--secondary); }
    .c-label { font-size: 11px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: .4px; }
    .c-value { font-size: 15px; font-weight: 500; }

    /* Social links */
    .social-links { display: flex; gap: 10px; flex-wrap: wrap; }
    .social-link {
      width: 44px; height: 44px; border-radius: 10px; border: 1.5px solid transparent;
      display: flex; align-items: center; justify-content: center;
      text-decoration: none; background: #f5f5f5; transition: all .3s;
    }
    .social-link i { font-size: 22px; }
    .social-link.linkedin { color: #0a66c2; }
    .social-link.linkedin:hover { background: #0a66c2; color: #fff; }
    .social-link.instagram { color: #e4405f; }
    .social-link.instagram:hover { background: #e4405f; color: #fff; }
    .social-link.twitter { color: #1da1f2; }
    .social-link.twitter:hover { background: #1da1f2; color: #fff; }
    .social-link.facebook { color: #1877f2; }
    .social-link.facebook:hover { background: #1877f2; color: #fff; }
    .social-link.youtube { color: #ff0000; }
    .social-link.youtube:hover { background: #ff0000; color: #fff; }

    /* Gallery / Video carousel */
    .carousel-card { border-radius: 12px; overflow: hidden; position: relative; }
    .carousel-card img { width: 100%; height: 240px; object-fit: cover; display: block; }
    .carousel-control-prev, .carousel-control-next {
      width: 36px; height: 36px;
      background: rgba(255,255,255,.9) !important;
      border-radius: 50%; top: 50%; transform: translateY(-50%);
      position: absolute; border: none; cursor: pointer;
      display: flex; align-items: center; justify-content: center;
    }
    .carousel-control-prev { left: 8px; }
    .carousel-control-next { right: 8px; }
    .carousel-counter {
      position: absolute; top: 10px; right: 10px;
      background: rgba(0,0,0,.55); color: #fff;
      font-size: 11px; font-weight: 700; padding: 3px 8px;
      border-radius: 20px;
    }

    /* Video iframe */
    .video-frame { width: 100%; border-radius: 10px; display: block; }

    /* ── Multi-item section styles ── */
    /* Photo grid for section items */
    .cs-photo-grid {
      display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; margin-bottom: 10px;
    }
    .cs-photo-item {
      position: relative; border-radius: 10px; overflow: hidden;
      aspect-ratio: 1; background: #f0f0f0;
    }
    .cs-photo-item img {
      width: 100%; height: 100%; object-fit: cover; display: block;
    }
    .cs-item-del {
      position: absolute; top: 5px; right: 5px;
      width: 24px; height: 24px; border-radius: 50%;
      background: rgba(220,53,69,.85); color: #fff; border: none;
      font-size: 11px; cursor: pointer; display: flex; align-items: center; justify-content: center;
      transition: background .2s; z-index: 2;
    }
    .cs-item-del:hover { background: #dc3545; }
    /* Video item row */
    .cs-video-row {
      margin-bottom: 10px; border-radius: 10px; overflow: hidden;
      border: 1px solid var(--border-light); background: #fafafa;
    }
    .cs-video-iframe { width: 100%; height: 180px; display: block; border: none; }
    .cs-video-foot {
      display: flex; align-items: center; justify-content: flex-end;
      padding: 6px 10px; background: #fafafa;
    }
    /* Doc item */
    .cs-doc-row {
      display: flex; align-items: center; gap: 10px;
      padding: 10px 12px; background: #fafafa;
      border-radius: 10px; border: 1px solid var(--border-light);
      margin-bottom: 8px;
    }
    .cs-doc-row:last-child { margin-bottom: 0; }
    /* Add-more bar */
    .cs-add-bar {
      margin-top: 10px; display: flex; gap: 8px; flex-wrap: wrap;
    }
    .cs-add-btn {
      display: inline-flex; align-items: center; gap: 5px;
      padding: 7px 14px; background: rgba(249,129,30,.1); color: var(--primary);
      border: 1.5px dashed var(--primary); border-radius: 8px;
      font-size: 13px; font-weight: 600; cursor: pointer; font-family: inherit;
      transition: all .2s;
    }
    .cs-add-btn:hover { background: rgba(249,129,30,.2); }
    /* Inline video-add form */
    .cs-inline-add {
      display: none; margin-top: 10px; padding: 12px;
      background: #fafafa; border-radius: 10px; border: 1px solid var(--border-light);
    }
    .cs-inline-add.open { display: block; }
    .cs-inline-add-row {
      display: flex; gap: 8px; align-items: center; margin-bottom: 8px;
    }
    .cs-inline-add-row:last-child { margin-bottom: 0; }

    /* Documents */
    .doc-item {
      display: flex; align-items: center; gap: 12px;
      padding: 11px 14px; background: #fafafa;
      border-radius: 10px; border: 1px solid var(--border-light);
      margin-bottom: 8px;
    }
    .doc-icon {
      width: 38px; height: 38px; background: rgba(249,129,30,.1);
      border-radius: 8px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;
    }
    .doc-icon i { color: var(--primary); font-size: 18px; }
    .doc-name { font-size: 14px; font-weight: 600; }
    .doc-size { font-size: 12px; color: var(--text-muted); }
    .doc-del-btn {
      margin-left: auto; width: 30px; height: 30px; border: none;
      background: rgba(220,53,69,.1); border-radius: 6px;
      color: #dc3545; cursor: pointer; font-size: 13px;
      display: flex; align-items: center; justify-content: center;
      flex-shrink: 0; transition: background .2s;
    }
    .doc-del-btn:hover { background: rgba(220,53,69,.2); }

    /* === MODALS === */
    .modal-hdr {
      background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
      padding: 24px 28px; color: #fff;
    }
    .modal-hdr h5 { font-size: 20px; font-weight: 700; margin: 0; display: flex; align-items: center; gap: 10px; }
    .modal-hdr p { font-size: 13px; opacity: .9; margin: 6px 0 0; }
    .modal-ftr {
      padding: 16px 28px; background: #f9f9f7;
      border-top: 1px solid #e8e8e8;
      display: flex; justify-content: flex-end; gap: 10px;
    }
    .btn-modal-cancel {
      padding: 10px 22px; border-radius: 10px;
      background: #f0f0f0; color: var(--text-dark);
      border: 1px solid #e0e0e0; font-weight: 600; cursor: pointer;
      font-family: inherit; font-size: 13px;
    }
    .btn-modal-save {
      padding: 10px 22px; border-radius: 10px;
      background: var(--primary); color: #fff;
      border: none; font-weight: 600; cursor: pointer;
      font-family: inherit; font-size: 13px;
      box-shadow: 0 4px 12px rgba(249,129,30,.3);
      transition: all .2s;
    }
    .btn-modal-save:hover { background: #e57316; }
    .btn-modal-save:disabled { opacity: .6; cursor: not-allowed; }

    .form-lbl { font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: .4px; margin-bottom: 5px; display: block; }
    .form-inp, .form-ta {
      width: 100%; padding: 10px 13px; border: 1.5px solid #e8e8e8;
      border-radius: 9px; font-family: inherit; font-size: 14px;
      color: var(--text-dark); transition: border-color .2s;
    }
    .form-inp:focus, .form-ta:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(249,129,30,.1); }
    .form-ta { resize: vertical; min-height: 100px; }
    .form-group { margin-bottom: 14px; }

    /* Upload zone */
    .upload-zone {
      border: 2px dashed #e0e0e0; border-radius: 12px;
      padding: 28px 16px; text-align: center;
      cursor: pointer; transition: all .2s;
      background: #fafafa;
    }
    .upload-zone:hover { border-color: var(--primary); background: rgba(249,129,30,.04); }
    .upload-zone i { font-size: 36px; color: var(--primary); display: block; margin-bottom: 8px; }

    /* Theme grid */
    .theme-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
    .theme-opt {
      border: 2px solid #e8e8e8; border-radius: 10px; padding: 12px;
      cursor: pointer; text-align: center; transition: all .2s;
    }
    .theme-opt:hover, .theme-opt.active { border-color: var(--primary); background: rgba(249,129,30,.06); }
    .theme-preview { display: flex; gap: 3px; height: 28px; border-radius: 6px; overflow: hidden; margin-bottom: 8px; }
    .theme-preview span { flex: 1; }
    .theme-name { font-size: 12px; font-weight: 700; }

    /* Gallery list in modal */
    .gallery-list-item {
      display: flex; align-items: center; gap: 10px;
      padding: 10px; background: #fafafa; border-radius: 8px;
      border: 1px solid #e8e8e8; margin-bottom: 8px;
    }
    .gallery-thumb { width: 48px; height: 48px; border-radius: 6px; object-fit: cover; flex-shrink: 0; }
    .gallery-del-btn {
      margin-left: auto; width: 28px; height: 28px; border: none;
      background: rgba(220,53,69,.1); border-radius: 6px;
      color: #dc3545; cursor: pointer; font-size: 12px;
      display: flex; align-items: center; justify-content: center;
      flex-shrink: 0;
    }


    /* Toast */
    .toast-bar {
      position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);
      background: #191919; color: #fff; padding: 10px 20px;
      border-radius: 24px; font-size: 13px; font-weight: 600;
      z-index: 9999; opacity: 0; transition: opacity .3s;
      pointer-events: none; white-space: nowrap;
    }
    .toast-bar.show { opacity: 1; }

    /* Save CTA */
    .save-contact-cta {
      display: flex; align-items: center; justify-content: center;
      gap: 8px; padding: 13px 24px; margin-top: 16px;
      background: var(--primary); color: #fff;
      border: none; border-radius: 12px;
      font-family: inherit; font-size: 16px; font-weight: 600;
      cursor: pointer; width: 100%;
      box-shadow: 0 4px 14px rgba(249,129,30,.3);
      transition: all .25s;
    }
    .save-contact-cta:hover { background: #e57316; }

    /* === FORMAT SELECTOR === */
    .format-selector { display:flex; gap:12px; margin-bottom:16px; justify-content:center; flex-wrap:wrap; }
    .format-btn {
      padding:10px 24px; border-radius:8px; border:2px solid var(--primary);
      background:transparent; color:var(--primary); font-weight:600;
      font-size:13px; cursor:pointer; transition:all .2s; font-family:inherit;
    }
    .format-btn.active { background:var(--primary); color:#fff; }
    .format-btn:hover { transform:translateY(-1px); }
    .flip-hint {
      text-align:center; font-size:12px; color:var(--text-muted);
      margin-bottom:12px; display:flex; align-items:center; justify-content:center; gap:5px;
    }

    /* === BUSINESS CARD === */
    .card-container {
      perspective:1200px; width:min(550px,92vw);
      aspect-ratio:550/320; cursor:pointer; margin:0 auto 10px;
      display:flex;
    }
    .card-inner {
      position:relative; width:100%; height:100%;
      transition:transform .7s cubic-bezier(.4,0,.2,1); transform-style:preserve-3d;
    }
    .card-container.flipped .card-inner { transform:rotateY(180deg); }
    .card-front, .card-back {
      position:absolute; width:100%; height:100%;
      backface-visibility:hidden; border-radius:16px;
      overflow:hidden; box-shadow:0 8px 32px rgba(0,0,0,.1);
      background:#fff; border:1px solid var(--border-light);
    }
    .card-back { transform:rotateY(180deg); }
    .card-front::before {
      content:''; position:absolute; top:0; left:0;
      width:6px; height:100%;
      background:linear-gradient(180deg,var(--primary),var(--secondary));
      border-radius:16px 0 0 16px;
    }
    .card-back::before {
      content:''; position:absolute; top:0; right:0; width:180px; height:100%;
      background:linear-gradient(135deg,transparent 40%,rgba(249,129,30,.05) 40%,rgba(249,129,30,.05) 60%,rgba(0,168,84,.05) 60%);
    }
    .card-front-content {
      display:flex; align-items:center; height:100%;
      padding:clamp(14px,4%,28px); gap:clamp(10px,3%,24px);
    }
    .card-front-text {
      flex:1; display:flex; flex-direction:column; justify-content:center; min-width:0;
    }
    .card-front-logo-row {
      display:flex; align-items:center; gap:8px; margin-bottom:10px; flex-wrap:wrap;
    }
    .card-front-name {
      font-family:'Playfair Display',serif; font-size:clamp(16px,4.5vw,24px);
      font-weight:700; color:var(--text-dark); margin:0 0 4px; line-height:1.2; word-break:break-word;
    }
    .card-front-designation {
      font-size:clamp(10px,2.2vw,13px); color:var(--primary);
      font-weight:600; margin:0; letter-spacing:.3px; word-break:break-word;
    }
    .card-front-company {
      font-size:clamp(10px,2vw,13px); font-weight:600;
      color:var(--text-muted); letter-spacing:.5px;
    }
    .person-photo {
      border-radius:50%;
      background:linear-gradient(135deg,var(--primary),var(--secondary));
      display:flex; align-items:center; justify-content:center; flex-shrink:0;
      box-shadow:0 4px 16px rgba(249,129,30,.25);
      overflow:hidden;
    }
    .person-photo-card  { width:clamp(70px,18vw,110px); height:clamp(70px,18vw,110px); }
    .person-photo-large {
      width:clamp(80px,20vw,110px); height:clamp(80px,20vw,110px);
      margin-top:12px; margin-bottom:16px;
    }
    .card-back-content {
      padding:clamp(14px,4%,24px); height:100%;
      display:flex; flex-direction:column; justify-content:center;
      position:relative; z-index:1;
    }
    .card-back-header { margin-bottom:10px; }
    .card-back-company-name {
      font-family:'Playfair Display',serif; font-size:clamp(13px,3.5vw,17px);
      font-weight:700; color:var(--text-dark); word-break:break-word;
    }
    .card-back-divider {
      width:36px; height:3px;
      background:linear-gradient(90deg,var(--primary),var(--secondary));
      border-radius:2px; margin:8px 0 12px;
    }
    .card-contact-row {
      display:flex; align-items:center; gap:10px; padding:5px 0;
    }
    .card-contact-icon {
      width:24px; height:24px; min-width:24px; border-radius:6px;
      background:rgba(249,129,30,.08); border:1px solid rgba(249,129,30,.15);
      display:flex; align-items:center; justify-content:center; flex-shrink:0;
    }
    .card-contact-icon i { font-size:12px; color:var(--primary); }
    .card-contact-text {
      font-size:clamp(10px,2.2vw,12.5px); color:var(--text-dark);
      font-weight:500; word-break:break-word; min-width:0; overflow:hidden; text-overflow:ellipsis;
    }

    /* === STANDEE === */
    .standee-container {
      width:min(360px,68vw); aspect-ratio:1/1.4; margin:0 auto; display:flex;
    }
    .standee-wrapper {
      background:#fff; border-radius:12px;
      box-shadow:0 8px 32px rgba(0,0,0,.08); border:1px solid var(--border-light);
      display:flex; flex-direction:column; align-items:center;
      position:relative; overflow:hidden; width:100%;
      padding:clamp(20px,5%,32px) clamp(14px,4%,24px);
    }
    .standee-accent {
      position:absolute; top:0; left:0; width:100%; height:6px;
      background:linear-gradient(90deg,var(--primary),var(--secondary));
    }
    .standee-name {
      font-family:'Playfair Display',serif; font-size:clamp(18px,5vw,26px);
      font-weight:700; color:var(--text-dark); margin:0 0 4px; line-height:1.2;
      text-align:center; word-break:break-word;
    }
    .standee-designation {
      font-size:clamp(11px,2.8vw,14px); color:var(--primary); font-weight:600;
      margin:0 0 14px; letter-spacing:.3px; text-align:center; word-break:break-word;
    }
    .standee-company-row {
      display:flex; align-items:center; gap:8px;
      justify-content:center; margin-bottom:14px; flex-wrap:wrap;
    }
    .standee-company-text {
      font-size:clamp(10px,2vw,12px); font-weight:700;
      color:var(--text-muted); letter-spacing:.5px; text-align:center;
    }
    .standee-contact { display:flex; flex-direction:column; gap:7px; width:100%; }
    .standee-contact-row { display:flex; align-items:center; gap:10px; justify-content:center; }
    .standee-contact-icon {
      width:22px; height:22px; min-width:22px; border-radius:6px;
      background:rgba(249,129,30,.08); border:1px solid rgba(249,129,30,.15);
      display:flex; align-items:center; justify-content:center;
    }
    .standee-contact-icon i { font-size:11px; color:var(--primary); }
    .standee-contact-text { font-size:clamp(11px,2.5vw,13px); color:var(--text-dark); font-weight:500; }

    /* === DOWNLOAD ROW === */
    .download-section {
      display:flex; align-items:center; justify-content:center;
      gap:10px; margin-top:16px; flex-wrap:wrap;
    }
    .side-label {
      background:rgba(249,129,30,.1); color:var(--primary); font-size:11px;
      font-weight:700; padding:4px 12px; border-radius:20px; letter-spacing:.4px;
    }
    .download-btn {
      display:flex; align-items:center; gap:7px;
      padding:9px 20px; border-radius:10px; border:none;
      font-family:inherit; font-size:13px; font-weight:600; cursor:pointer; transition:all .2s;
    }
    .png-btn { background:var(--primary); color:#fff; box-shadow:0 4px 12px rgba(249,129,30,.3); }
    .png-btn:hover { background:#e57316; }
    .pdf-btn { background:var(--secondary); color:#fff; box-shadow:0 4px 12px rgba(0,168,84,.25); }
    .pdf-btn:hover { opacity:.9; }

    /* === SECTION TYPE BUTTONS === */
    .section-type-btn {
      background:#f9f9f7; border:1.5px solid #e8e8e8; border-radius:12px;
      padding:20px 14px; cursor:pointer; transition:all .2s;
      display:flex; flex-direction:column; align-items:center; gap:8px; font-family:inherit;
    }
    .section-type-btn:hover {
      border-color:var(--primary); background:rgba(249,129,30,.04);
      transform:translateY(-2px); box-shadow:0 4px 12px rgba(249,129,30,.1);
    }
    .section-type-icon { font-size:30px; color:var(--primary); display:flex; align-items:center; }
    .section-type-label { font-size:14px; font-weight:700; color:var(--text-dark); }
    .section-type-desc { font-size:11px; color:var(--text-muted); text-align:center; }

    @media print {
      body > *:not(.print-target) { display: none !important; }
      .print-target { display: block !important; }
    }
  </style>
</head>
<body>

<?php


// CSRF token for AJAX
$csrf      = csrf_field();
$csrfName  = csrf_token();
$csrfHash  = csrf_hash();

// QR code URL for the avatar flip-back panel
$qrImgUrl  = (!empty($qr) && !empty($qr['file_path']))
    ? base_url('uploads/' . $qr['file_path']) . '?t=' . time()
    : '';

?>

<div class="app-shell" id="appShell">

  <!-- Cover Banner -->
  <div class="cover-banner">
    
    <div class="banner-menu">
      <button class="menu-btn" id="menuToggleBtn" title="Menu">
        <i class="bi bi-list"></i>
      </button>
    </div>
  </div>

  <!-- Profile Main Card -->
  <div class="profile-main-card">
    <div class="hero-left">
      <!-- Flip-card avatar: hover flips to "Change Photo"; click triggers file picker -->
	  
	   <!-- Flip avatar: front = photo, back = QR -->
        <div class="profile-avatar-wrap">
          <div class="profile-avatar" id="profileAvatar" onclick="this.classList.toggle('flipped')"
               title="Tap to flip and scan QR">
            <div class="profile-avatar-front">
              <img src="<?= esc($photoUrl) ?>" alt="" loading="lazy">
            </div>
            <div class="profile-avatar-back">
              <?php if ($qrImgUrl): ?>
              <img src="<?= esc($qrImgUrl) ?>" alt="QR Code"
                   style="image-rendering:pixelated;width:90%;height:90%;object-fit:contain">
              <?php else: ?>
              <div class="initials-qr">
                <i class="bi bi-qr-code" style="font-size:32px;color:#ccc"></i><br>
                <span style="font-size:10px">No QR</span>
              </div>
              <?php endif; ?>
            </div>
          </div>
          <?php if ($qrImgUrl): ?>
          <div style="font-size:10px;color:var(--text-muted);text-align:center;margin-top:6px">
            <i class="bi bi-arrow-repeat me-1"></i>Tap to flip &amp; scan
          </div>
          <?php endif; ?>
        </div>
	  
	  
	  
      <div class="avatar-upload-status" id="avatarUploadStatus"></div>
      <!-- File input lives here (outside all modals) so it works regardless of modal state -->
      <input type="file" id="photoFileInput" accept="image/*" style="display:none;"
             onchange="previewAndUploadPhoto(this)">
      <div class="profile-name" id="displayName"><?= esc($p['name']) ?></div>
      <div class="profile-designation" id="displayDesignation"><?= esc($p['designation'] ?? '') ?></div>
      <div class="profile-company">
        <i class="bi bi-building"></i>
        <span id="displayCompany"><?= esc($p['company_name'] ?? '') ?></span>
      </div>
    </div>

    <!-- Edit Profile Info button -->
    <button class="save-contact-cta mt-3" onclick="openInfoModal()">
      <i class="bi bi-pencil-fill"></i> Edit Profile Info
    </button>
  </div>

  <!-- About -->
  <div class="section-card">
    <div class="section-header">
      <div class="section-title"><i class="bi bi-info-circle-fill"></i> About</div>
      <button class="edit-btn" onclick="openAboutModal()" title="Edit About"><i class="bi bi-pencil-fill"></i></button>
    </div>
    <div class="about-text" id="displayAbout"><?= esc($p['about_us'] ?? '') ?: '<span style="color:#bbb;font-style:italic;">No description yet. Click edit to add.</span>' ?></div>
    <?php if (strlen($p['about_us'] ?? '') > 200): ?>
    <button class="read-more-btn" onclick="this.previousElementSibling.classList.toggle('expanded'); this.textContent = this.previousElementSibling.classList.contains('expanded') ? 'Read Less' : 'Read More';">Read More</button>
    <?php endif; ?>
  </div>

  <!-- Contact -->
  <div class="section-card">
    <div class="section-header">
      <div class="section-title"><i class="bi bi-telephone-fill"></i> Contact</div>
      <button class="edit-btn" onclick="openContactModal()" title="Edit Contact"><i class="bi bi-pencil-fill"></i></button>
    </div>
    <?php $mobile = ($p['mobile_country_code'] ?? '') . ' ' . ($p['mobile'] ?? ''); ?>
    <div class="contact-row">
      <div class="contact-icon"><i class="bi bi-telephone-fill"></i></div>
      <div><div class="c-label">Phone</div><div class="c-value" id="displayPhone"><?= esc(trim($mobile)) ?: '—' ?></div></div>
    </div>
    <div class="contact-row">
      <div class="contact-icon"><i class="bi bi-envelope-fill"></i></div>
      <div><div class="c-label">Email</div><div class="c-value" id="displayEmail"><?= esc($p['email'] ?? '') ?: '—' ?></div></div>
    </div>
    <div class="contact-row">
      <div class="contact-icon"><i class="bi bi-globe2"></i></div>
      <div><div class="c-label">Website</div><div class="c-value" id="displayWebsite"><?= esc($p['website'] ?? '') ?: '—' ?></div></div>
    </div>
    <div class="contact-row">
      <div class="contact-icon"><i class="bi bi-geo-alt-fill"></i></div>
      <div><div class="c-label">Address</div><div class="c-value" id="displayAddress"><?= esc($p['address'] ?? '') ?: '—' ?></div></div>
    </div>
  </div>

  <!-- Social Links -->
  <div class="section-card">
    <div class="section-header">
      <div class="section-title"><i class="bi bi-share-fill"></i> Connect</div>
      <button class="edit-btn" onclick="openSocialModal()" title="Edit Social"><i class="bi bi-pencil-fill"></i></button>
    </div>
    <div class="social-links" id="socialLinksWrap">
      <?php if ($p['linkedin']): ?><a href="<?= esc($p['linkedin']) ?>" target="_blank" class="social-link linkedin"><i class="bi bi-linkedin"></i></a><?php endif; ?>
      <?php if ($p['instagram']): ?><a href="<?= esc($p['instagram']) ?>" target="_blank" class="social-link instagram"><i class="bi bi-instagram"></i></a><?php endif; ?>
      <?php if ($p['twitter']): ?><a href="<?= esc($p['twitter']) ?>" target="_blank" class="social-link twitter"><i class="bi bi-twitter"></i></a><?php endif; ?>
      <?php if ($p['facebook']): ?><a href="<?= esc($p['facebook']) ?>" target="_blank" class="social-link facebook"><i class="bi bi-facebook"></i></a><?php endif; ?>
      <?php if ($p['youtube']): ?><a href="<?= esc($p['youtube']) ?>" target="_blank" class="social-link youtube"><i class="bi bi-youtube"></i></a><?php endif; ?>
      <?php if (! $p['linkedin'] && ! $p['instagram'] && ! $p['twitter'] && ! $p['facebook'] && ! $p['youtube']): ?>
        <span style="color:#bbb;font-style:italic;font-size:13px;">No social links added yet.</span>
      <?php endif; ?>
    </div>
  </div>

  <!-- Gallery -->
  <?php if (count($gallery) > 0): ?>
  <div class="section-card" id="gallerySectionCard">
    <div class="section-header">
      <div class="section-title"><i class="bi bi-images"></i> Gallery</div>
      <button class="edit-btn" onclick="openGalleryModal()" title="Edit Gallery"><i class="bi bi-pencil-fill"></i></button>
    </div>
    <div class="carousel-card" id="galleryCarousel">
      <span class="carousel-counter" id="galleryCounter">1 / <?= count($gallery) ?></span>
      <?php foreach ($gallery as $idx => $img): ?>
      <div class="carousel-item-g" data-idx="<?= $idx ?>" style="display:<?= $idx === 0 ? 'block' : 'none' ?>;">
        <img src="<?= base_url('uploads/' . $img['file_path']) ?>" alt="Gallery">
      </div>
      <?php endforeach; ?>
      <?php if (count($gallery) > 1): ?>
      <button class="carousel-control-prev" onclick="gallerySlidePrev()"><i class="bi bi-chevron-left" style="filter:invert(0) brightness(.3);"></i></button>
      <button class="carousel-control-next" onclick="gallerySlideNext()"><i class="bi bi-chevron-right" style="filter:invert(0) brightness(.3);"></i></button>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- Videos -->
  <?php if (count($videos) > 0): ?>
  <div class="section-card" id="videoSectionCard">
    <div class="section-header">
      <div class="section-title"><i class="bi bi-play-circle-fill"></i> Videos</div>
      <button class="edit-btn" onclick="openVideoModal()" title="Edit Videos"><i class="bi bi-pencil-fill"></i></button>
    </div>
    <div id="videoCarouselWrap">
      <?php foreach ($videos as $idx => $vid): ?>
      <div class="carousel-item-v" data-idx="<?= $idx ?>" style="display:<?= $idx === 0 ? 'block' : 'none' ?>;">
        <iframe class="video-frame" height="220" src="<?= esc($vid['url'] ?? '') ?>" frameborder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowfullscreen></iframe>
        <?php if ($vid['title']): ?>
        <div style="padding:8px 0 0; font-size:14px; font-weight:600; color:var(--text-dark);"><?= esc($vid['title']) ?></div>
        <?php endif; ?>
      </div>
      <?php endforeach; ?>
      <?php if (count($videos) > 1): ?>
      <div style="display:flex;gap:8px;justify-content:center;margin-top:12px;">
        <button class="carousel-control-prev" style="position:static;transform:none;" onclick="videoSlidePrev()"><i class="bi bi-chevron-left" style="filter:brightness(.3);"></i></button>
        <span id="videoCounter" style="font-size:12px;font-weight:700;background:rgba(0,0,0,.55);color:#fff;padding:4px 10px;border-radius:20px;">1 / <?= count($videos) ?></span>
        <button class="carousel-control-next" style="position:static;transform:none;" onclick="videoSlideNext()"><i class="bi bi-chevron-right" style="filter:brightness(.3);"></i></button>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- Documents -->
  <?php if (count($documents) > 0): ?>
  <div class="section-card" id="docSectionCard">
    <div class="section-header">
      <div class="section-title"><i class="bi bi-file-earmark-pdf"></i> Documents</div>
      <button class="edit-btn" onclick="openDocModal()" title="Edit Documents"><i class="bi bi-pencil-fill"></i></button>
    </div>
    <div id="docListWrap">
      <?php foreach ($documents as $doc): ?>
      <div class="doc-item" id="doc-<?= $doc['id'] ?>">
        <div class="doc-icon"><i class="bi bi-file-earmark-pdf"></i></div>
        <div>
          <div class="doc-name"><?= esc($doc['title'] ?: $doc['original_name']) ?></div>
          <div class="doc-size"><?= $doc['file_size'] ? round($doc['file_size']/1048576, 1) . ' MB' : '' ?></div>
        </div>
        <a href="<?= base_url('uploads/' . $doc['file_path']) ?>" target="_blank" class="doc-del-btn" style="color:var(--secondary);background:rgba(0,168,84,.1);" title="Download">
          <i class="bi bi-download"></i>
        </a>
        <button class="doc-del-btn" onclick="deleteMedia(<?= $doc['id'] ?>, 'doc-<?= $doc['id'] ?>')" title="Delete">
          <i class="bi bi-trash"></i>
        </button>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- ═══════════════════════════════════════════════════════════
       CUSTOM SECTIONS (dynamically added by member)
       ═══════════════════════════════════════════════════════════ -->
  <?php
  $sectionIconMap = [
      'text'     => 'bi-file-text',
      'photo'    => 'bi-image',
      'video'    => 'bi-play-circle-fill',
      'document' => 'bi-file-earmark-pdf',
  ];
  ?>
  <?php foreach ($sections as $sec): ?>
  <?php
    $secIcon  = $sectionIconMap[$sec['section_type']] ?? 'bi-puzzle';
    $secItems = $sectionItems[$sec['id']] ?? [];
  ?>
  <div class="section-card" id="custom-section-<?= $sec['id'] ?>">
    <div class="section-header">
      <div class="section-title">
        <i class="bi <?= $secIcon ?>"></i> <?= esc($sec['title']) ?>
      </div>
      <div style="display:flex;gap:6px;flex-shrink:0;">
        <!-- Edit button (title / content only) -->
        <button class="edit-btn cs-edit-btn"
                data-sec-id="<?= $sec['id'] ?>"
                data-sec-type="<?= $sec['section_type'] ?>"
                data-sec-title="<?= esc($sec['title'], 'attr') ?>"
                <?php if ($sec['section_type'] === 'text'): ?>
                data-sec-content="<?= esc($sec['content'] ?? '', 'attr') ?>"
                <?php endif; ?>
                onclick="openEditSectionModal(this)" title="Edit section">
          <i class="bi bi-pencil-fill"></i>
        </button>
        <!-- Delete section button -->
        <button class="edit-btn" style="background:#dc3545;"
                onclick="deleteCustomSection(<?= $sec['id'] ?>)" title="Delete section">
          <i class="bi bi-trash"></i>
        </button>
      </div>
    </div>

    <!-- cs-body -->
    <div class="cs-body">

      <?php if ($sec['section_type'] === 'text'): ?>
        <div class="about-text expanded" style="display:block;-webkit-line-clamp:unset;overflow:visible;">
          <?= nl2br(esc($sec['content'] ?? '')) ?>
        </div>

      <?php elseif ($sec['section_type'] === 'photo'): ?>
        <?php $totalPhotos = count($secItems); ?>
        <!-- Photo carousel -->
        <div class="carousel-card" id="cs-photo-car-<?= $sec['id'] ?>"
             style="margin-bottom:10px;<?= $totalPhotos === 0 ? 'display:none;' : '' ?>">
          <span class="carousel-counter" id="cs-photo-count-<?= $sec['id'] ?>">
            <?= $totalPhotos > 0 ? '1 / ' . $totalPhotos : '' ?>
          </span>
          <?php foreach ($secItems as $idx => $item): ?>
          <div class="cs-car-photo-item" id="sitem-<?= $item['id'] ?>"
               style="display:<?= $idx === 0 ? 'block' : 'none' ?>;">
            <img src="<?= base_url('uploads/' . esc($item['file_path'])) ?>"
                 alt="photo" loading="lazy"
                 style="width:100%;height:240px;object-fit:cover;display:block;">
            <button class="cs-item-del" title="Delete"
                    onclick="deleteSectionPhoto(<?= $item['id'] ?>, <?= $sec['id'] ?>)">
              <i class="bi bi-x"></i>
            </button>
          </div>
          <?php endforeach; ?>
          <button class="carousel-control-prev" id="cs-photo-prev-<?= $sec['id'] ?>"
                  style="display:<?= $totalPhotos > 1 ? '' : 'none' ?>;"
                  onclick="csPhotoSlide(<?= $sec['id'] ?>, -1)">
            <i class="bi bi-chevron-left" style="filter:brightness(.3);"></i>
          </button>
          <button class="carousel-control-next" id="cs-photo-next-<?= $sec['id'] ?>"
                  style="display:<?= $totalPhotos > 1 ? '' : 'none' ?>;"
                  onclick="csPhotoSlide(<?= $sec['id'] ?>, 1)">
            <i class="bi bi-chevron-right" style="filter:brightness(.3);"></i>
          </button>
        </div>
        <!-- Add more photos -->
        <div class="cs-add-bar">
          <button class="cs-add-btn" onclick="document.getElementById('sec-photo-input-<?= $sec['id'] ?>').click()">
            <i class="bi bi-plus-lg"></i> Add Photos
          </button>
        </div>
        <input type="file" id="sec-photo-input-<?= $sec['id'] ?>" accept="image/*" multiple style="display:none;"
               onchange="addSectionPhotos(<?= $sec['id'] ?>, this)">

      <?php elseif ($sec['section_type'] === 'video'): ?>
        <?php $totalVids = count($secItems); ?>
        <!-- Video carousel -->
        <div class="carousel-card" id="cs-video-car-<?= $sec['id'] ?>"
             style="margin-bottom:10px;<?= $totalVids === 0 ? 'display:none;' : '' ?>">
          <span class="carousel-counter" id="cs-video-count-<?= $sec['id'] ?>">
            <?= $totalVids > 0 ? '1 / ' . $totalVids : '' ?>
          </span>
          <div id="cs-videos-<?= $sec['id'] ?>">
            <?php foreach ($secItems as $idx => $item): ?>
            <div class="cs-car-video-item" id="sitem-<?= $item['id'] ?>"
                 style="display:<?= $idx === 0 ? 'block' : 'none' ?>;">
              <iframe class="cs-video-iframe" src="<?= esc($item['url'] ?? '') ?>"
                      frameborder="0"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                      allowfullscreen loading="lazy"></iframe>
              <div class="cs-video-foot">
                <button class="cs-item-del" style="position:static;width:28px;height:28px;border-radius:6px;"
                        title="Delete"
                        onclick="deleteSectionVideo(<?= $item['id'] ?>, <?= $sec['id'] ?>)">
                  <i class="bi bi-trash"></i>
                </button>
              </div>
            </div>
            <?php endforeach; ?>
          </div>
          <button class="carousel-control-prev" id="cs-video-prev-<?= $sec['id'] ?>"
                  style="display:<?= $totalVids > 1 ? '' : 'none' ?>;"
                  onclick="csVideoSlide(<?= $sec['id'] ?>, -1)">
            <i class="bi bi-chevron-left" style="filter:brightness(.3);"></i>
          </button>
          <button class="carousel-control-next" id="cs-video-next-<?= $sec['id'] ?>"
                  style="display:<?= $totalVids > 1 ? '' : 'none' ?>;"
                  onclick="csVideoSlide(<?= $sec['id'] ?>, 1)">
            <i class="bi bi-chevron-right" style="filter:brightness(.3);"></i>
          </button>
        </div>
        <!-- Inline add video -->
        <div class="cs-inline-add" id="cs-vid-add-<?= $sec['id'] ?>">
          <div class="cs-inline-add-row">
            <input type="url" class="form-inp" id="cs-vid-url-<?= $sec['id'] ?>"
                   placeholder="https://youtube.com/watch?v=…" style="flex:1;margin-bottom:0;">
            <button class="cs-add-btn" style="border-style:solid;flex-shrink:0;"
                    onclick="addSectionVideo(<?= $sec['id'] ?>)">
              <i class="bi bi-plus-lg"></i> Add
            </button>
          </div>
        </div>
        <div class="cs-add-bar">
          <button class="cs-add-btn" onclick="toggleCsVidAdd(<?= $sec['id'] ?>)">
            <i class="bi bi-plus-lg"></i> Add Video
          </button>
        </div>

      <?php elseif ($sec['section_type'] === 'document'): ?>
        <div id="cs-docs-<?= $sec['id'] ?>">
          <?php foreach ($secItems as $item): ?>
          <div class="cs-doc-row" id="sitem-<?= $item['id'] ?>">
            <div class="doc-icon"><i class="bi bi-file-earmark-pdf"></i></div>
            <div style="flex:1;min-width:0;">
              <div class="doc-name" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                <?= esc($item['original_name'] ?? 'Document') ?>
              </div>
              <div class="doc-size">
                <?= $item['file_size'] ? round($item['file_size']/1048576, 1) . ' MB' : '' ?>
              </div>
            </div>
            <?php if (!empty($item['file_path'])): ?>
            <a href="<?= base_url('uploads/' . esc($item['file_path'])) ?>" target="_blank"
               class="doc-del-btn" style="color:var(--secondary);background:rgba(0,168,84,.1);" title="Download">
              <i class="bi bi-download"></i>
            </a>
            <?php endif; ?>
            <button class="doc-del-btn" title="Delete"
                    onclick="deleteSectionItem(<?= $item['id'] ?>, 'sitem-<?= $item['id'] ?>')">
              <i class="bi bi-trash"></i>
            </button>
          </div>
          <?php endforeach; ?>
        </div>
        <!-- Add more documents -->
        <div class="cs-add-bar">
          <button class="cs-add-btn" onclick="document.getElementById('sec-doc-input-<?= $sec['id'] ?>').click()">
            <i class="bi bi-plus-lg"></i> Add Documents
          </button>
        </div>
        <input type="file" id="sec-doc-input-<?= $sec['id'] ?>"
               accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt" multiple style="display:none;"
               onchange="addSectionDocuments(<?= $sec['id'] ?>, this)">

      <?php endif; ?>
    </div><!-- /cs-body -->
  </div>
  <?php endforeach; ?>

  <!-- Anchor that new sections are inserted before -->
  <div id="customSectionsEnd"></div>

</div><!-- /app-shell -->

<!-- ============================================================
     DRAWER MENU
     ============================================================ -->
<div class="menu-overlay" id="menuOverlay"></div>
<div class="menu-drawer" id="menuDrawer">
  <div class="menu-drawer-header">
    <strong style="font-size:16px;">Menu</strong>
    <button class="menu-close-btn" id="menuCloseBtn"><i class="bi bi-x-lg"></i></button>
  </div>
  <ul class="menu-items">
    <li>
      <a href="#" class="menu-item-link" onclick="closeMenu(); openAddSectionModal(event)">
        <div class="menu-item-icon"><i class="bi bi-plus-circle"></i></div>
        <div><div class="menu-item-label">Add New Section</div><div class="menu-item-subtitle">Expand your profile</div></div>
      </a>
    </li>
    <li>
      <a href="#" class="menu-item-link" onclick="closeMenu(); openPrintModal(event)">
        <div class="menu-item-icon"><i class="bi bi-credit-card"></i></div>
        <div><div class="menu-item-label">Print Cards</div><div class="menu-item-subtitle">Business card &amp; standee</div></div>
      </a>
    </li>
    <div class="menu-divider"></div>
    <li>
      <div style="padding: 14px 20px;">
        <div style="font-size:13px;font-weight:700;color:var(--text-dark);margin-bottom:10px;display:flex;align-items:center;gap:8px;">
          <i class="bi bi-palette-fill" style="color:var(--primary);"></i> Theme
        </div>
        <div class="theme-grid" id="menuThemeGrid"></div>
      </div>
    </li>
    <div class="menu-divider"></div>
    <li>
      <a href="<?= site_url('member/logout') ?>" class="menu-item-link">
        <div class="menu-item-icon"><i class="bi bi-power"></i></div>
        <div><div class="menu-item-label">Logout</div></div>
      </a>
    </li>
  </ul>
</div>

<!-- ============================================================
     MODAL: Edit Profile Info + Photo
     ============================================================ -->
<div class="modal fade" id="infoModal" tabindex="-1" data-bs-backdrop="static">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-hdr">
        <h5><i class="bi bi-person-fill"></i> Edit Profile</h5>
        <p>Update your name, designation and company</p>
      </div>
      <div style="padding:20px;">
        <!-- Photo -->
        <div style="text-align:center;margin-bottom:20px;">
          <img id="modalAvatarPreview" src="<?= esc($photoUrl) ?>" alt=""
               style="width:90px;height:90px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);margin-bottom:10px;">
          <br>
          <!-- Triggers the same #photoFileInput that lives outside this modal -->
          <button type="button" class="btn-modal-save" style="padding:8px 18px;font-size:13px;"
                  onclick="document.getElementById('photoFileInput').click()">
            <i class="bi bi-camera-fill"></i> Change Photo
          </button>
        </div>
        <!-- Logo -->
        <div style="margin-bottom:16px;padding:12px;background:#fafafa;border-radius:10px;border:1px dashed #e0e0e0;">
          <div class="form-lbl" style="margin-bottom:8px;">Company Logo</div>
          <div style="display:flex;align-items:center;gap:12px;">
            <img id="logoPreview" src="<?= esc($logoUrl) ?>" alt="" style="height:40px;max-width:100px;object-fit:contain;display:<?= $logoUrl ? 'block' : 'none' ?>;">
            <button type="button" onclick="document.getElementById('logoFileInput').click()" style="background:none;border:1px solid #ddd;border-radius:8px;padding:6px 14px;font-size:12px;cursor:pointer;font-family:inherit;color:var(--text-dark);">
              <?= $logoUrl ? 'Change Logo' : 'Upload Logo' ?>
            </button>
          </div>
          <input type="file" id="logoFileInput" accept="image/*" style="display:none;" onchange="uploadLogo(this)">
        </div>
        <div class="form-group">
          <label class="form-lbl">Full Name *</label>
          <input type="text" class="form-inp" id="infoName" value="<?= esc($p['name']) ?>">
        </div>
        <div class="form-group">
          <label class="form-lbl">Designation</label>
          <input type="text" class="form-inp" id="infoDesignation" value="<?= esc($p['designation'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-lbl">Company Name</label>
          <input type="text" class="form-inp" id="infoCompany" value="<?= esc($p['company_name'] ?? '') ?>">
        </div>
      </div>
      <div class="modal-ftr">
        <button class="btn-modal-cancel" data-bs-dismiss="modal">Cancel</button>
        <button class="btn-modal-save" id="infoSaveBtn" onclick="saveInfo()">Save Changes</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================================================
     MODAL: Edit About
     ============================================================ -->
<div class="modal fade" id="aboutModal" tabindex="-1" data-bs-backdrop="static">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-hdr">
        <h5><i class="bi bi-info-circle-fill"></i> Edit About</h5>
        <p>Update your bio information</p>
      </div>
      <div style="padding:20px;">
        <div class="form-group">
          <label class="form-lbl">About Text</label>
          <textarea class="form-ta" id="aboutText" rows="6" placeholder="Write about yourself..."><?= esc($p['about_us'] ?? '') ?></textarea>
        </div>
      </div>
      <div class="modal-ftr">
        <button class="btn-modal-cancel" data-bs-dismiss="modal">Cancel</button>
        <button class="btn-modal-save" onclick="saveAbout()">Save Changes</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================================================
     MODAL: Edit Contact
     ============================================================ -->
<div class="modal fade" id="contactModal" tabindex="-1" data-bs-backdrop="static">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-hdr">
        <h5><i class="bi bi-telephone-fill"></i> Edit Contact</h5>
        <p>Update your contact details</p>
      </div>
      <div style="padding:20px;">
        <div class="form-group">
          <label class="form-lbl">Email</label>
          <input type="email" class="form-inp" id="contactEmail" value="<?= esc($p['email'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-lbl">Website</label>
          <input type="url" class="form-inp" id="contactWebsite" placeholder="https://example.com" value="<?= esc($p['website'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-lbl">Address</label>
          <input type="text" class="form-inp" id="contactAddress" value="<?= esc($p['address'] ?? '') ?>">
        </div>
        <p style="font-size:12px;color:var(--text-muted);margin-top:4px;"><i class="bi bi-info-circle"></i> Mobile number is managed by admin. Contact admin to change it.</p>
      </div>
      <div class="modal-ftr">
        <button class="btn-modal-cancel" data-bs-dismiss="modal">Cancel</button>
        <button class="btn-modal-save" onclick="saveContact()">Save Changes</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================================================
     MODAL: Edit Social Links
     ============================================================ -->
<div class="modal fade" id="socialModal" tabindex="-1" data-bs-backdrop="static">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-hdr">
        <h5><i class="bi bi-share-fill"></i> Edit Social Links</h5>
        <p>Update your social media profiles</p>
      </div>
      <div style="padding:20px;">
        <div class="form-group">
          <label class="form-lbl"><i class="bi bi-linkedin" style="color:#0a66c2;"></i> LinkedIn URL</label>
          <input type="url" class="form-inp" id="socialLinkedin" placeholder="https://linkedin.com/in/yourprofile" value="<?= esc($p['linkedin'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-lbl"><i class="bi bi-instagram" style="color:#e4405f;"></i> Instagram URL</label>
          <input type="url" class="form-inp" id="socialInstagram" placeholder="https://instagram.com/yourprofile" value="<?= esc($p['instagram'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-lbl"><i class="bi bi-twitter" style="color:#1da1f2;"></i> Twitter URL</label>
          <input type="url" class="form-inp" id="socialTwitter" placeholder="https://twitter.com/yourprofile" value="<?= esc($p['twitter'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-lbl"><i class="bi bi-facebook" style="color:#1877f2;"></i> Facebook URL</label>
          <input type="url" class="form-inp" id="socialFacebook" placeholder="https://facebook.com/yourprofile" value="<?= esc($p['facebook'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-lbl"><i class="bi bi-youtube" style="color:#ff0000;"></i> YouTube URL</label>
          <input type="url" class="form-inp" id="socialYoutube" placeholder="https://youtube.com/c/yourchannel" value="<?= esc($p['youtube'] ?? '') ?>">
        </div>
      </div>
      <div class="modal-ftr">
        <button class="btn-modal-cancel" data-bs-dismiss="modal">Cancel</button>
        <button class="btn-modal-save" onclick="saveSocial()">Save Changes</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================================================
     MODAL: Edit Gallery
     ============================================================ -->
<div class="modal fade" id="galleryModal" tabindex="-1" data-bs-backdrop="static">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-hdr">
        <h5><i class="bi bi-images"></i> Manage Gallery</h5>
        <p>Upload or remove photos</p>
      </div>
      <div style="padding:20px;max-height:60vh;overflow-y:auto;">
        <div id="galleryModalList">
          <?php foreach ($gallery as $img): ?>
          <div class="gallery-list-item" id="galleryItem-<?= $img['id'] ?>">
            <img src="<?= base_url('uploads/' . $img['file_path']) ?>" class="gallery-thumb" alt="">
            <div style="flex:1;min-width:0;">
              <div style="font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= esc($img['original_name'] ?? '') ?></div>
            </div>
            <button class="gallery-del-btn" onclick="deleteMedia(<?= $img['id'] ?>, 'galleryItem-<?= $img['id'] ?>')"><i class="bi bi-trash"></i></button>
          </div>
          <?php endforeach; ?>
          <?php if (empty($gallery)): ?>
          <p style="color:#bbb;text-align:center;font-style:italic;padding:20px 0;">No photos uploaded yet.</p>
          <?php endif; ?>
        </div>
        <!-- Upload zone -->
        <div class="upload-zone" onclick="document.getElementById('galleryFileInput').click()">
          <i class="bi bi-cloud-upload"></i>
          <div style="font-size:14px;font-weight:600;">Click to upload photos</div>
          <div style="font-size:12px;color:var(--text-muted);margin-top:4px;">JPG, PNG, WebP — max 5 MB each</div>
        </div>
        <input type="file" id="galleryFileInput" accept="image/*" multiple style="display:none;" onchange="uploadGalleryImages(this)">
        <div id="galleryUploadProgress" style="display:none;margin-top:10px;">
          <div style="height:4px;background:#e0e0e0;border-radius:4px;overflow:hidden;">
            <div style="height:100%;background:var(--primary);width:0;transition:width .3s;" id="galleryProgressBar"></div>
          </div>
          <div style="font-size:12px;color:var(--text-muted);margin-top:4px;" id="galleryProgressText">Uploading…</div>
        </div>
      </div>
      <div class="modal-ftr">
        <button class="btn-modal-cancel" data-bs-dismiss="modal">Done</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================================================
     MODAL: Edit Videos
     ============================================================ -->
<div class="modal fade" id="videoModal" tabindex="-1" data-bs-backdrop="static">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-hdr">
        <h5><i class="bi bi-play-circle-fill"></i> Manage Videos</h5>
        <p>Add YouTube / Vimeo URLs</p>
      </div>
      <div style="padding:20px;max-height:60vh;overflow-y:auto;">
        <div id="videoModalList">
          <?php foreach ($videos as $vid): ?>
          <div class="gallery-list-item" id="videoItem-<?= $vid['id'] ?>">
            <div style="width:48px;height:48px;background:#1a1a1a;border-radius:6px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
              <i class="bi bi-play-fill" style="color:#fff;font-size:18px;"></i>
            </div>
            <div style="flex:1;min-width:0;">
              <div style="font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= esc($vid['title'] ?: 'Video') ?></div>
            </div>
            <button class="gallery-del-btn" onclick="deleteMedia(<?= $vid['id'] ?>, 'videoItem-<?= $vid['id'] ?>')"><i class="bi bi-trash"></i></button>
          </div>
          <?php endforeach; ?>
          <?php if (empty($videos)): ?>
          <p style="color:#bbb;text-align:center;font-style:italic;padding:20px 0;" id="noVideosMsg">No videos added yet.</p>
          <?php endif; ?>
        </div>
        <!-- Add video form -->
        <div style="border-top:1px solid #f0f0f0;padding-top:16px;margin-top:10px;">
          <div style="font-size:13px;font-weight:700;margin-bottom:10px;">Add New Video</div>
          <div class="form-group">
            <label class="form-lbl">YouTube / Vimeo URL</label>
            <input type="url" class="form-inp" id="newVideoUrl" placeholder="https://youtube.com/watch?v=...">
          </div>
          <div class="form-group">
            <label class="form-lbl">Title (optional)</label>
            <input type="text" class="form-inp" id="newVideoTitle" placeholder="Video title">
          </div>
          <button class="btn-modal-save" style="width:100%;" onclick="addVideo()"><i class="bi bi-plus-lg"></i> Add Video</button>
        </div>
      </div>
      <div class="modal-ftr">
        <button class="btn-modal-cancel" data-bs-dismiss="modal">Done</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================================================
     MODAL: Edit Documents
     ============================================================ -->
<div class="modal fade" id="docModal" tabindex="-1" data-bs-backdrop="static">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-hdr">
        <h5><i class="bi bi-file-earmark-pdf"></i> Manage Documents</h5>
        <p>Upload or remove documents</p>
      </div>
      <div style="padding:20px;max-height:60vh;overflow-y:auto;">
        <div id="docModalList">
          <?php foreach ($documents as $doc): ?>
          <div class="gallery-list-item" id="docItem-<?= $doc['id'] ?>">
            <div style="width:48px;height:48px;background:linear-gradient(135deg,#ff4444,#cc0000);border-radius:6px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
              <i class="bi bi-file-earmark-pdf" style="color:#fff;font-size:20px;"></i>
            </div>
            <div style="flex:1;min-width:0;">
              <div style="font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= esc($doc['title'] ?: $doc['original_name']) ?></div>
              <div style="font-size:11px;color:var(--text-muted);"><?= $doc['file_size'] ? round($doc['file_size']/1048576, 1) . ' MB' : '' ?></div>
            </div>
            <button class="gallery-del-btn" onclick="deleteMedia(<?= $doc['id'] ?>, 'docItem-<?= $doc['id'] ?>'); document.getElementById('doc-<?= $doc['id'] ?>')?.remove()"><i class="bi bi-trash"></i></button>
          </div>
          <?php endforeach; ?>
          <?php if (empty($documents)): ?>
          <p style="color:#bbb;text-align:center;font-style:italic;padding:20px 0;" id="noDocsMsg">No documents uploaded yet.</p>
          <?php endif; ?>
        </div>
        <!-- Upload zone -->
        <div style="border-top:1px solid #f0f0f0;padding-top:16px;margin-top:10px;">
          <div class="form-group">
            <label class="form-lbl">Document Title</label>
            <input type="text" class="form-inp" id="docTitle" placeholder="e.g., Resume 2024">
          </div>
          <div class="upload-zone" onclick="document.getElementById('docFileInput').click()">
            <i class="bi bi-file-earmark-arrow-up"></i>
            <div style="font-size:14px;font-weight:600;">Click to upload document</div>
            <div style="font-size:12px;color:var(--text-muted);margin-top:4px;">PDF, Word, Excel — max 20 MB</div>
          </div>
          <input type="file" id="docFileInput" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt" style="display:none;" onchange="uploadDocument(this)">
        </div>
      </div>
      <div class="modal-ftr">
        <button class="btn-modal-cancel" data-bs-dismiss="modal">Done</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================================================
     MODAL: Add New Section  (two-step flow)
     ============================================================ -->
<div class="modal fade" id="addSectionModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.15);">
      <div class="modal-hdr">
        <h5><i class="bi bi-plus-circle-fill"></i> Add New Section</h5>
        <p>Choose what to add to your profile</p>
      </div>
      <div style="padding:20px;">

        <!-- STEP 1: Type grid -->
        <div id="sectionTypeSelection" style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;">
          <button class="section-type-btn" onclick="selectSectionType('text')">
            <div class="section-type-icon"><i class="bi bi-file-text"></i></div>
            <div class="section-type-label">Text</div>
            <div class="section-type-desc">Add text content</div>
          </button>
          <button class="section-type-btn" onclick="selectSectionType('photo')">
            <div class="section-type-icon"><i class="bi bi-image"></i></div>
            <div class="section-type-label">Photo</div>
            <div class="section-type-desc">Add photos</div>
          </button>
          <button class="section-type-btn" onclick="selectSectionType('video')">
            <div class="section-type-icon"><i class="bi bi-play-circle"></i></div>
            <div class="section-type-label">Video</div>
            <div class="section-type-desc">Add videos</div>
          </button>
          <button class="section-type-btn" onclick="selectSectionType('document')">
            <div class="section-type-icon"><i class="bi bi-file-pdf"></i></div>
            <div class="section-type-label">Document</div>
            <div class="section-type-desc">Add documents</div>
          </button>
        </div>

        <!-- STEP 2a: Text form -->
        <div id="textSectionForm" style="display:none;">
          <div class="form-group">
            <label class="form-lbl">Section Title *</label>
            <input type="text" class="form-inp" id="textSectionTitle" placeholder="e.g., Skills, Experience, Achievements">
          </div>
          <div class="form-group">
            <label class="form-lbl">Content *</label>
            <textarea class="form-ta" id="textSectionContent" rows="5" placeholder="Write your content here…"></textarea>
          </div>
        </div>

        <!-- STEP 2b: Photo form -->
        <div id="photoSectionForm" style="display:none;">
          <div class="form-group">
            <label class="form-lbl">Caption (optional)</label>
            <input type="text" class="form-inp" id="photoSectionTitle" placeholder="e.g., Portfolio, Work, Projects">
          </div>
          <div class="upload-zone" id="photoUploadZone" onclick="document.getElementById('photoSectionInput').click()" style="margin-bottom:0;">
            <i class="bi bi-cloud-upload"></i>
            <div style="font-size:14px;font-weight:600;">Click to upload photos</div>
            <div style="font-size:12px;color:var(--text-muted);margin-top:4px;">JPG, PNG, WebP — max 5 MB each · multiple allowed</div>
          </div>
          <!-- multiple files supported -->
          <input type="file" id="photoSectionInput" accept="image/*" multiple style="display:none;" onchange="handlePhotosPreview(this)">
          <div id="photoSectionPreviewList" style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px;"></div>
        </div>

        <!-- STEP 2c: Video form -->
        <div id="videoSectionForm" style="display:none;">
          <div class="form-group">
            <label class="form-lbl">Section Title (optional)</label>
            <input type="text" class="form-inp" id="videoSectionTitle" placeholder="e.g., Tutorials, Demos">
          </div>
          <div class="form-group">
            <label class="form-lbl">YouTube / Vimeo URLs *</label>
            <!-- Dynamic URL rows -->
            <div id="videoUrlRows">
              <div class="cs-inline-add-row" style="display:flex;gap:8px;margin-bottom:8px;" id="vidRow0">
                <input type="url" class="form-inp" name="vidUrl0" style="flex:1;margin-bottom:0;" placeholder="https://youtube.com/watch?v=…">
                <button type="button" style="width:36px;height:42px;border:none;border-radius:8px;background:#f0f0f0;cursor:pointer;color:#999;flex-shrink:0;" onclick="removeVidRow(this)">
                  <i class="bi bi-x-lg"></i>
                </button>
              </div>
            </div>
            <button type="button" class="cs-add-btn" style="margin-top:4px;border-style:dashed;" onclick="addVidRow()">
              <i class="bi bi-plus-lg"></i> Add Another URL
            </button>
          </div>
        </div>

        <!-- STEP 2d: Document form -->
        <div id="documentSectionForm" style="display:none;">
          <div class="form-group">
            <label class="form-lbl">Section Title</label>
            <input type="text" class="form-inp" id="docSectionTitle" placeholder="e.g., Resume 2024, Certificates">
          </div>
          <div class="upload-zone" id="docUploadZone" onclick="document.getElementById('docSectionInput').click()" style="margin-bottom:0;">
            <i class="bi bi-file-earmark-arrow-up"></i>
            <div style="font-size:14px;font-weight:600;">Click to upload documents</div>
            <div style="font-size:12px;color:var(--text-muted);margin-top:4px;">PDF, Word, Excel — max 20 MB each · multiple allowed</div>
          </div>
          <!-- multiple files supported -->
          <input type="file" id="docSectionInput" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt" multiple style="display:none;" onchange="handleDocsPreview(this)">
          <div id="docSectionPreviewList" style="margin-top:8px;"></div>
        </div>

      </div>
      <div class="modal-ftr">
        <button class="btn-modal-cancel" id="backToTypesBtn" style="display:none;" onclick="backToSectionTypes()">
          <i class="bi bi-arrow-left"></i> Back
        </button>
        <button class="btn-modal-cancel" data-bs-dismiss="modal" onclick="resetAddSectionModal_()">Cancel</button>
        <button class="btn-modal-save" id="addSectionBtn" onclick="submitAddSection()">Add Section</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================================================
     MODAL: Print Cards / Visiting Card
     ============================================================ -->
<?php $mobile = trim(($p['mobile_country_code'] ?? '') . ' ' . ($p['mobile'] ?? '')); ?>
<div class="modal fade" id="printModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-dialog-centered modal-lg" style="max-width:860px;">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-hdr">
        <h5><i class="bi bi-credit-card"></i> Visiting Card</h5>
        <p>Professional print-ready business card</p>
      </div>
      <div style="padding:24px;background:#fafaf8;">

        <!-- Format tabs -->
        <div class="format-selector">
          <button id="fmtCard"    class="format-btn active" onclick="switchFormat('card')">Business Card</button>
          <button id="fmtStandee" class="format-btn"        onclick="switchFormat('standee')">Standee</button>
        </div>

        <!-- Flip hint (card only) -->
        <p class="flip-hint" id="flipHint"><i class="bi bi-arrow-repeat"></i> Click card to flip</p>

        <!-- ── BUSINESS CARD ── -->
        <div class="card-container" id="cardContainer" onclick="this.classList.toggle('flipped')">
          <div class="card-inner">
            <!-- FRONT -->
            <div class="card-front">
              <div class="card-front-content">
                <div class="card-front-text">
                  <div class="card-front-logo-row">
                    <?php if ($logoUrl): ?>
                      <img src="<?= esc($logoUrl) ?>" style="max-height:32px;max-width:110px;object-fit:contain;">
                    <?php else: ?>
                      <span class="card-front-company"><?= esc($p['company_name'] ?? '') ?></span>
                    <?php endif; ?>
                  </div>
                  <h2 class="card-front-name"><?= esc($p['name']) ?></h2>
                  <p class="card-front-designation"><?= esc($p['designation'] ?? '') ?></p>
                </div>
                <div class="person-photo person-photo-card">
                  <?php if (!empty($p['profile_photo'])): ?>
                    <img src="<?= esc($photoUrl) ?>" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">
                  <?php else: ?>
                    <i class="bi bi-person-fill" style="font-size:clamp(26px,8vw,44px);color:#fff;"></i>
                  <?php endif; ?>
                </div>
              </div>
            </div>
            <!-- BACK -->
            <div class="card-back">
              <div class="card-back-content">
                <?php if ($p['company_name'] ?? ''): ?>
                <div class="card-back-header">
                  <div class="card-back-company-name"><?= esc($p['company_name']) ?></div>
                  <div class="card-back-divider"></div>
                </div>
                <?php endif; ?>
                <?php if ($mobile): ?><div class="card-contact-row"><div class="card-contact-icon"><i class="bi bi-telephone-fill"></i></div><span class="card-contact-text"><?= esc($mobile) ?></span></div><?php endif; ?>
                <?php if ($p['email']): ?><div class="card-contact-row"><div class="card-contact-icon"><i class="bi bi-envelope-fill"></i></div><span class="card-contact-text"><?= esc($p['email']) ?></span></div><?php endif; ?>
                <?php if (!empty($p['website'])): ?><div class="card-contact-row"><div class="card-contact-icon"><i class="bi bi-globe2"></i></div><span class="card-contact-text"><?= esc($p['website']) ?></span></div><?php endif; ?>
                <?php if ($p['address']): ?><div class="card-contact-row"><div class="card-contact-icon"><i class="bi bi-geo-alt-fill"></i></div><span class="card-contact-text"><?= esc($p['address']) ?></span></div><?php endif; ?>
              </div>
            </div>
          </div>
        </div>

        <!-- ── STANDEE ── -->
        <div class="standee-container" id="standeeContainer" style="display:none;">
          <div class="standee-wrapper">
            <div class="standee-accent"></div>
            <div class="person-photo person-photo-large">
              <?php if (!empty($p['profile_photo'])): ?>
                <img src="<?= esc($photoUrl) ?>" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">
              <?php else: ?>
                <i class="bi bi-person-fill" style="font-size:clamp(30px,9vw,50px);color:#fff;"></i>
              <?php endif; ?>
            </div>
            <h2 class="standee-name"><?= esc($p['name']) ?></h2>
            <p class="standee-designation"><?= esc($p['designation'] ?? '') ?></p>
            <?php if ($p['company_name'] ?? ''): ?>
            <div class="standee-company-row">
              <?php if ($logoUrl): ?><img src="<?= esc($logoUrl) ?>" style="max-height:24px;max-width:80px;object-fit:contain;"><?php endif; ?>
              <span class="standee-company-text"><?= esc(strtoupper($p['company_name'])) ?></span>
            </div>
            <?php endif; ?>
            <div class="standee-contact">
              <?php if ($mobile): ?><div class="standee-contact-row"><div class="standee-contact-icon"><i class="bi bi-telephone-fill"></i></div><span class="standee-contact-text"><?= esc($mobile) ?></span></div><?php endif; ?>
              <?php if ($p['email']): ?><div class="standee-contact-row"><div class="standee-contact-icon"><i class="bi bi-envelope-fill"></i></div><span class="standee-contact-text"><?= esc($p['email']) ?></span></div><?php endif; ?>
              <?php if (!empty($p['website'])): ?><div class="standee-contact-row"><div class="standee-contact-icon"><i class="bi bi-globe2"></i></div><span class="standee-contact-text"><?= esc($p['website']) ?></span></div><?php endif; ?>
            </div>
          </div>
        </div>

        <!-- Side label + Download buttons -->
        <div class="download-section">
          <span class="side-label" id="sideIndicator">Front Side</span>
          <button class="download-btn png-btn" onclick="downloadCardPng()">
            <i class="bi bi-download"></i> Download PNG
          </button>
          <button class="download-btn pdf-btn" onclick="printCard()">
            <i class="bi bi-printer"></i> Print
          </button>
        </div>

      </div>
      <div class="modal-ftr">
        <button class="btn-modal-cancel" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================================================
     MODAL: Edit Custom Section
     ============================================================ -->
<div class="modal fade" id="editSectionModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0" style="border-radius:16px;overflow:hidden;">
      <div class="modal-hdr">
        <h5 id="editSecModalTitle"><i class="bi bi-pencil-fill"></i> Edit Section</h5>
        <p id="editSecModalSubtitle">Update section content</p>
      </div>
      <div style="padding:20px;max-height:70vh;overflow-y:auto;">

        <!-- Hidden state -->
        <input type="hidden" id="editSecId">
        <input type="hidden" id="editSecType">

        <!-- Title (all types) -->
        <div class="form-group">
          <label class="form-lbl">Section Title *</label>
          <input type="text" class="form-inp" id="editSecTitle" placeholder="Section title">
        </div>

        <!-- ── TEXT fields ── -->
        <div id="editSecTextFields" style="display:none;">
          <div class="form-group">
            <label class="form-lbl">Content *</label>
            <textarea class="form-ta" id="editSecContent" rows="7"
                      placeholder="Write your content here…"></textarea>
          </div>
        </div>

        <!-- Note: for photo / video / document sections, only the title is edited here.
             Individual items are added/deleted directly on the section card. -->
        <div id="editSecMediaNote" style="display:none;padding:10px 14px;background:#fff8ee;
             border-radius:8px;border:1px solid rgba(249,129,30,.3);font-size:13px;color:var(--text-muted);margin-top:4px;">
          <i class="bi bi-info-circle" style="color:var(--primary);"></i>
          To add or remove individual items, use the <strong>Add / delete buttons</strong> directly on the section card.
        </div>

      </div><!-- /padding -->
      <div class="modal-ftr">
        <button class="btn-modal-cancel" data-bs-dismiss="modal"
                onclick="resetEditSectionModal()">Cancel</button>
        <button class="btn-modal-save" id="editSecSaveBtn"
                onclick="saveEditSection()">Save Changes</button>
      </div>
    </div>
  </div>
</div>

<!-- Toast -->
<div class="toast-bar" id="toastBar"></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

<script>
// ── CSRF token (refreshed on each response) ──────────────────────────────────
var CSRF_NAME = '<?= $csrfName ?>';
var CSRF_HASH = '<?= $csrfHash ?>';

function csrfHeaders() {
  var h = {};
  h[CSRF_NAME] = CSRF_HASH;
  return h;
}

// ── Toast ─────────────────────────────────────────────────────────────────────
function toast(msg, isErr) {
  var el = document.getElementById('toastBar');
  el.textContent = msg;
  el.style.background = isErr ? '#c0392b' : '#191919';
  el.classList.add('show');
  setTimeout(function() { el.classList.remove('show'); }, 3000);
}

// ── AJAX helper ───────────────────────────────────────────────────────────────
// Always uses FormData so CI4's CSRF filter finds the token in POST fields
// and getPost() reads all values correctly regardless of content.
async function ajaxPost(url, data) {
  var fd;
  if (data instanceof FormData) {
    fd = data;
  } else {
    fd = new FormData();
    Object.keys(data).forEach(function(k) {
      if (data[k] !== null && data[k] !== undefined) fd.append(k, data[k]);
    });
  }
  // Always inject the current CSRF token as a form field
  fd.append(CSRF_NAME, CSRF_HASH);

  try {
    var res  = await fetch(url, { method: 'POST', body: fd });
    var json = await res.json();
    // CI4 rotates the CSRF hash after each request — keep it fresh
    if (json[CSRF_NAME])  CSRF_HASH = json[CSRF_NAME];
    if (json.csrf_hash)   CSRF_HASH = json.csrf_hash;
    return json;
  } catch(e) {
    console.error('ajaxPost error:', e);
    return { success: false, message: 'Network error. Please try again.' };
  }
}

// ── DRAWER MENU ───────────────────────────────────────────────────────────────
var menuDrawer  = document.getElementById('menuDrawer');
var menuOverlay = document.getElementById('menuOverlay');

function openMenu() {
  menuDrawer.classList.add('active');
  menuOverlay.classList.add('active');
  document.body.style.overflow = 'hidden';
}
function closeMenu() {
  menuDrawer.classList.remove('active');
  menuOverlay.classList.remove('active');
  document.body.style.overflow = '';
}
document.getElementById('menuToggleBtn').addEventListener('click', openMenu);
document.getElementById('menuCloseBtn').addEventListener('click', closeMenu);
menuOverlay.addEventListener('click', closeMenu);
document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeMenu(); });

// ── MODAL HELPERS ─────────────────────────────────────────────────────────────
function openPhotoModal()   { new bootstrap.Modal(document.getElementById('infoModal')).show(); }
function openInfoModal()    { new bootstrap.Modal(document.getElementById('infoModal')).show(); }
function openAboutModal()   { new bootstrap.Modal(document.getElementById('aboutModal')).show(); }
function openContactModal() { new bootstrap.Modal(document.getElementById('contactModal')).show(); }
function openSocialModal()  { new bootstrap.Modal(document.getElementById('socialModal')).show(); }
function openGalleryModal() { new bootstrap.Modal(document.getElementById('galleryModal')).show(); }
function openVideoModal()   { new bootstrap.Modal(document.getElementById('videoModal')).show(); }
function openDocModal()     { new bootstrap.Modal(document.getElementById('docModal')).show(); }
function openAddSectionModal(e) {
  if (e) e.preventDefault();
  resetAddSectionModal_();
  new bootstrap.Modal(document.getElementById('addSectionModal')).show();
}
function openPrintModal(e)  { if(e) e.preventDefault(); new bootstrap.Modal(document.getElementById('printModal')).show(); }
function closeModals() {
  document.querySelectorAll('.modal.show').forEach(function(m) { bootstrap.Modal.getInstance(m)?.hide(); });
}

// ── SAVE: Profile Info ────────────────────────────────────────────────────────
async function saveInfo() {
  var name = document.getElementById('infoName').value.trim();
  if (!name) { toast('Name is required.', true); return; }
  var btn = document.getElementById('infoSaveBtn');
  btn.disabled = true; btn.textContent = 'Saving…';

  var res = await ajaxPost('<?= site_url('member/profile/save-info') ?>', {
    name:         name,
    designation:  document.getElementById('infoDesignation').value.trim(),
    company_name: document.getElementById('infoCompany').value.trim()
  });

  btn.disabled = false; btn.textContent = 'Save Changes';
  if (res.success) {
    document.getElementById('displayName').textContent        = name;
    document.getElementById('displayDesignation').textContent = document.getElementById('infoDesignation').value.trim();
    document.getElementById('displayCompany').textContent     = document.getElementById('infoCompany').value.trim();
    bootstrap.Modal.getInstance(document.getElementById('infoModal')).hide();
    toast('Profile info updated!');
  } else {
    toast(res.message || 'Save failed.', true);
  }
}

// ── SAVE: About ────────────────────────────────────────────────────────────────
async function saveAbout() {
  var text = document.getElementById('aboutText').value.trim();
  var res = await ajaxPost('<?= site_url('member/profile/save-about') ?>', { about_us: text });
  if (res.success) {
    document.getElementById('displayAbout').textContent = text || 'No description yet. Click edit to add.';
    bootstrap.Modal.getInstance(document.getElementById('aboutModal')).hide();
    toast('About section updated!');
  } else {
    toast(res.message || 'Save failed.', true);
  }
}

// ── SAVE: Contact ──────────────────────────────────────────────────────────────
async function saveContact() {
  var res = await ajaxPost('<?= site_url('member/profile/save-contact') ?>', {
    email:   document.getElementById('contactEmail').value.trim(),
    website: document.getElementById('contactWebsite').value.trim(),
    address: document.getElementById('contactAddress').value.trim()
  });
  if (res.success) {
    document.getElementById('displayEmail').textContent   = document.getElementById('contactEmail').value.trim() || '—';
    document.getElementById('displayWebsite').textContent = document.getElementById('contactWebsite').value.trim() || '—';
    document.getElementById('displayAddress').textContent = document.getElementById('contactAddress').value.trim() || '—';
    bootstrap.Modal.getInstance(document.getElementById('contactModal')).hide();
    toast('Contact info updated!');
  } else {
    toast(res.message || 'Save failed.', true);
  }
}

// ── SAVE: Social ───────────────────────────────────────────────────────────────
async function saveSocial() {
  var data = {
    linkedin:  document.getElementById('socialLinkedin').value.trim(),
    instagram: document.getElementById('socialInstagram').value.trim(),
    twitter:   document.getElementById('socialTwitter').value.trim(),
    facebook:  document.getElementById('socialFacebook').value.trim(),
    youtube:   document.getElementById('socialYoutube').value.trim()
  };
  var res = await ajaxPost('<?= site_url('member/profile/save-social') ?>', data);
  if (res.success) {
    // Rebuild social links
    var wrap = document.getElementById('socialLinksWrap');
    wrap.innerHTML = '';
    var map = [
      {key:'linkedin',  cls:'linkedin',  icon:'bi-linkedin'},
      {key:'instagram', cls:'instagram', icon:'bi-instagram'},
      {key:'twitter',   cls:'twitter',   icon:'bi-twitter'},
      {key:'facebook',  cls:'facebook',  icon:'bi-facebook'},
      {key:'youtube',   cls:'youtube',   icon:'bi-youtube'},
    ];
    var any = false;
    map.forEach(function(item) {
      if (data[item.key]) {
        any = true;
        wrap.innerHTML += '<a href="'+data[item.key]+'" target="_blank" class="social-link '+item.cls+'"><i class="bi '+item.icon+'"></i></a>';
      }
    });
    if (!any) wrap.innerHTML = '<span style="color:#bbb;font-style:italic;font-size:13px;">No social links added yet.</span>';
    bootstrap.Modal.getInstance(document.getElementById('socialModal')).hide();
    toast('Social links updated!');
  } else {
    toast(res.message || 'Save failed.', true);
  }
}

// ── UPLOAD: Profile Photo ──────────────────────────────────────────────────────
async function previewAndUploadPhoto(input) {
  if (!input.files[0]) return;
  var file  = input.files[0];
  var wrap  = document.getElementById('avatarFlipWrap');
  var status = document.getElementById('avatarUploadStatus');

  // 1. Instant local preview via FileReader (before upload completes)
  var reader = new FileReader();
  reader.onload = function(e) {
    document.getElementById('mainAvatarImg').src = e.target.result;
    // Also update modal preview if the infoModal is currently open
    var mp = document.getElementById('modalAvatarPreview');
    if (mp) mp.src = e.target.result;
  };
  reader.readAsDataURL(file);

  // 2. Show uploading state on the flip card
  if (wrap)   wrap.classList.add('uploading');
  if (status) status.textContent = 'Uploading…';

  // 3. Upload to server
  var fd = new FormData();
  fd.append('photo', file);
  var res = await ajaxPost('<?= site_url('member/profile/upload-photo') ?>', fd);

  // 4. Remove uploading state
  if (wrap)  { wrap.classList.remove('uploading'); }
  if (status) status.textContent = '';
  // Reset file input so the same file can be re-selected if needed
  input.value = '';

  if (res.success) {
    // Update all photo references with the server-confirmed URL
    document.getElementById('mainAvatarImg').src = res.url;
    var mp = document.getElementById('modalAvatarPreview');
    if (mp) mp.src = res.url;
    // Also update the card photo inside the print modal (if rendered)
    document.querySelectorAll('.person-photo img').forEach(function(img) {
      img.src = res.url;
    });

    // Refresh QR code on the avatar flip-back panel
    if (res.qr_updated && res.qr_url) {
      var qrImg    = document.getElementById('avatarQrImg');
      var qrWrap   = document.getElementById('avatarQrWrap');
      var noQrWrap = document.getElementById('avatarNoQrWrap');
      if (qrImg)    qrImg.src = res.qr_url;
      if (qrWrap)   qrWrap.style.display   = 'flex';
      if (noQrWrap) noQrWrap.style.display = 'none';
      toast('Photo updated & QR code regenerated!');
    } else {
      toast('Photo updated!');
    }
  } else {
    toast(res.message || 'Upload failed.', true);
  }
}

// ── UPLOAD: Company Logo ───────────────────────────────────────────────────────
async function uploadLogo(input) {
  if (!input.files[0]) return;
  var fd = new FormData();
  fd.append('logo', input.files[0]);
  var res = await ajaxPost('<?= site_url('member/profile/upload-logo') ?>', fd);
  if (res.success) {
    var prev = document.getElementById('logoPreview');
    prev.src = res.url; prev.style.display = 'block';
    toast('Logo updated!');
  } else {
    toast(res.message || 'Upload failed.', true);
  }
}

// ── UPLOAD: Gallery Images ─────────────────────────────────────────────────────
async function uploadGalleryImages(input) {
  if (!input.files.length) return;
  var files = Array.from(input.files);
  var prog  = document.getElementById('galleryUploadProgress');
  var bar   = document.getElementById('galleryProgressBar');
  var txt   = document.getElementById('galleryProgressText');
  prog.style.display = 'block';

  for (var i = 0; i < files.length; i++) {
    txt.textContent = 'Uploading ' + (i+1) + ' of ' + files.length + '…';
    bar.style.width = Math.round(((i+1) / files.length) * 100) + '%';
    var fd = new FormData();
    fd.append('image', files[i]);
    var res = await ajaxPost('<?= site_url('member/profile/upload-gallery') ?>', fd);
    if (res.success) {
      // Add to modal list
      document.getElementById('galleryModalList').insertAdjacentHTML('beforeend',
        '<div class="gallery-list-item" id="galleryItem-'+res.id+'">'+
        '<img src="'+res.url+'" class="gallery-thumb" alt="">'+
        '<div style="flex:1;min-width:0;"><div style="font-size:13px;font-weight:600;">Photo '+res.id+'</div></div>'+
        '<button class="gallery-del-btn" onclick="deleteMedia('+res.id+', \'galleryItem-'+res.id+'\')"><i class="bi bi-trash"></i></button>'+
        '</div>');
      // Remove "no photos" message
      document.querySelectorAll('#galleryModalList p').forEach(function(p) { p.remove(); });
    } else {
      toast(res.message, true);
    }
  }
  prog.style.display = 'none';
  bar.style.width = '0';
  input.value = '';
  toast('Gallery updated! Refresh page to see changes.');
}

// ── ADD: Video ─────────────────────────────────────────────────────────────────
async function addVideo() {
  var url   = document.getElementById('newVideoUrl').value.trim();
  var title = document.getElementById('newVideoTitle').value.trim();
  if (!url) { toast('Please enter a video URL.', true); return; }
  var res = await ajaxPost('<?= site_url('member/profile/add-video') ?>', { url: url, title: title });
  if (res.success) {
    document.getElementById('videoModalList').insertAdjacentHTML('beforeend',
      '<div class="gallery-list-item" id="videoItem-'+res.id+'">'+
      '<div style="width:48px;height:48px;background:#1a1a1a;border-radius:6px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">'+
      '<i class="bi bi-play-fill" style="color:#fff;font-size:18px;"></i></div>'+
      '<div style="flex:1;min-width:0;"><div style="font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'+(title||'Video')+'</div></div>'+
      '<button class="gallery-del-btn" onclick="deleteMedia('+res.id+', \'videoItem-'+res.id+'\')"><i class="bi bi-trash"></i></button>'+
      '</div>');
    document.getElementById('newVideoUrl').value   = '';
    document.getElementById('newVideoTitle').value = '';
    document.querySelectorAll('#videoModalList p').forEach(function(p) { p.remove(); });
    toast('Video added! Refresh page to see it.');
  } else {
    toast(res.message || 'Failed to add video.', true);
  }
}

// ── UPLOAD: Document ───────────────────────────────────────────────────────────
async function uploadDocument(input) {
  if (!input.files[0]) return;
  var title = document.getElementById('docTitle').value.trim();
  var fd = new FormData();
  fd.append('document', input.files[0]);
  fd.append('title', title || input.files[0].name);
  var res = await ajaxPost('<?= site_url('member/profile/upload-document') ?>', fd);
  if (res.success) {
    document.getElementById('docModalList').insertAdjacentHTML('beforeend',
      '<div class="gallery-list-item" id="docItem-'+res.id+'">'+
      '<div style="width:48px;height:48px;background:linear-gradient(135deg,#ff4444,#cc0000);border-radius:6px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">'+
      '<i class="bi bi-file-earmark-pdf" style="color:#fff;font-size:20px;"></i></div>'+
      '<div style="flex:1;min-width:0;"><div style="font-size:13px;font-weight:600;">'+(res.title||'Document')+'</div>'+
      '<div style="font-size:11px;color:var(--text-muted);">'+res.size+'</div></div>'+
      '<button class="gallery-del-btn" onclick="deleteMedia('+res.id+', \'docItem-'+res.id+'\')"><i class="bi bi-trash"></i></button>'+
      '</div>');
    document.getElementById('docTitle').value = '';
    input.value = '';
    document.querySelectorAll('#docModalList p').forEach(function(p) { p.remove(); });
    toast('Document uploaded! Refresh page to see it.');
  } else {
    toast(res.message || 'Upload failed.', true);
  }
}

// ── DELETE: Media ──────────────────────────────────────────────────────────────
async function deleteMedia(id, domId) {
  if (!confirm('Delete this item?')) return;
  var res = await ajaxPost('<?= site_url('member/profile/delete-media/') ?>'+id, {});
  if (res.success) {
    // Remove from modal
    var el = document.getElementById(domId);
    if (el) el.remove();
    // Also remove from main page view
    var mainEl = document.getElementById('doc-'+id) || document.getElementById('galleryItem-'+id);
    if (mainEl) mainEl.remove();
    toast('Deleted.');
  } else {
    toast(res.message || 'Delete failed.', true);
  }
}

// ── GALLERY CAROUSEL ───────────────────────────────────────────────────────────
var galleryCurrent = 0;
var galleryItems   = document.querySelectorAll('.carousel-item-g');
var galleryCounter = document.getElementById('galleryCounter');

function galleryShow(idx) {
  galleryItems.forEach(function(el, i) { el.style.display = i === idx ? 'block' : 'none'; });
  if (galleryCounter) galleryCounter.textContent = (idx+1) + ' / ' + galleryItems.length;
  galleryCurrent = idx;
}
function gallerySlideNext() { galleryShow((galleryCurrent+1) % galleryItems.length); }
function gallerySlidePrev() { galleryShow((galleryCurrent - 1 + galleryItems.length) % galleryItems.length); }

// ── VIDEO CAROUSEL ─────────────────────────────────────────────────────────────
var videoCurrent = 0;
var videoItems   = document.querySelectorAll('.carousel-item-v');
var videoCounter = document.getElementById('videoCounter');

function videoShow(idx) {
  videoItems.forEach(function(el, i) { el.style.display = i === idx ? 'block' : 'none'; });
  if (videoCounter) videoCounter.textContent = (idx+1) + ' / ' + videoItems.length;
  videoCurrent = idx;
}
function videoSlideNext() { videoShow((videoCurrent+1) % videoItems.length); }
function videoSlidePrev() { videoShow((videoCurrent - 1 + videoItems.length) % videoItems.length); }

// ── THEME SYSTEM ───────────────────────────────────────────────────────────────
var THEMES = {
  sunset:  { name:'Sunset',  primary:'#f9811e', secondary:'#00a854', preview:['#f9811e','#e06800','#00a854'] },
  ocean:   { name:'Ocean',   primary:'#0066cc', secondary:'#00bfff', preview:['#0066cc','#0052a3','#00bfff'] },
  forest:  { name:'Forest',  primary:'#2d6a4f', secondary:'#40916c', preview:['#2d6a4f','#1b4332','#40916c'] },
  grape:   { name:'Grape',   primary:'#7209b7', secondary:'#c77dff', preview:['#7209b7','#5a189a','#c77dff'] },
  coral:   { name:'Coral',   primary:'#ff6b6b', secondary:'#ffa500', preview:['#ff6b6b','#ee5a52','#ffa500'] }
};

// Server-stored theme for this profile (loaded at page render time)
var SAVED_THEME = '<?= esc($profile['theme'] ?? 'sunset') ?>';

function applyTheme(name, persist) {
  var t = THEMES[name];
  if (!t) return;
  document.documentElement.style.setProperty('--primary',   t.primary);
  document.documentElement.style.setProperty('--secondary', t.secondary);
  localStorage.setItem('member_theme', name);   // local fallback

  // Save to DB so it persists after logout / new device
  if (persist !== false) {
    ajaxPost('<?= site_url('member/profile/save-theme') ?>', { theme: name })
      .then(function(res) {
        if (res.success) { SAVED_THEME = name; }
      });
  }
}

function renderMenuThemes() {
  var grid = document.getElementById('menuThemeGrid');
  if (!grid) return;
  // Use server-stored theme as the source of truth; fall back to localStorage
  var active = (SAVED_THEME && THEMES[SAVED_THEME]) ? SAVED_THEME
             : (localStorage.getItem('member_theme') || 'sunset');
  grid.innerHTML = '';
  Object.keys(THEMES).forEach(function(key) {
    var t = THEMES[key];
    var isActive = active === key;
    var opt = document.createElement('div');
    opt.className = 'theme-opt' + (isActive ? ' active' : '');
    opt.innerHTML =
      '<div class="theme-preview">' +
      t.preview.map(function(c) { return '<span style="background:'+c+'"></span>'; }).join('') +
      '</div><div class="theme-name">'+t.name+'</div>';
    opt.onclick = function() {
      document.querySelectorAll('.theme-opt').forEach(function(el) { el.classList.remove('active'); });
      opt.classList.add('active');
      applyTheme(key);  // persist = true (default) → saves to DB
    };
    grid.appendChild(opt);
  });
}

// Restore theme on load — server value takes precedence over localStorage.
// Pass persist=false so we don't trigger a redundant DB save on load.
(function() {
  var theme = (SAVED_THEME && THEMES[SAVED_THEME]) ? SAVED_THEME
            : (localStorage.getItem('member_theme') || 'sunset');
  applyTheme(theme, false);
})();

// ── PRINT CARD ─────────────────────────────────────────────────────────────────
var currentFormat = 'card';

function switchFormat(fmt) {
  currentFormat = fmt;
  var cardEl    = document.getElementById('cardContainer');
  var standeeEl = document.getElementById('standeeContainer');
  var flipHint  = document.getElementById('flipHint');
  cardEl.style.display    = fmt === 'card'    ? 'flex' : 'none';
  standeeEl.style.display = fmt === 'standee' ? 'flex' : 'none';
  flipHint.style.display  = fmt === 'card'    ? 'flex' : 'none';
  document.getElementById('fmtCard').classList.toggle('active',    fmt === 'card');
  document.getElementById('fmtStandee').classList.toggle('active', fmt === 'standee');
}

function printCard() {
  var target = currentFormat === 'card'
    ? document.getElementById('cardContainer')
    : document.querySelector('.standee-wrapper');
  if (!target) return;
  var styles = Array.from(document.styleSheets).map(function(s) {
    try { return Array.from(s.cssRules).map(function(r) { return r.cssText; }).join('\n'); } catch(e) { return ''; }
  }).join('\n');
  var w = window.open('', '_blank');
  w.document.write('<html><head><title>Print</title><style>'+styles+'body{margin:20px;display:flex;justify-content:center;align-items:center;min-height:90vh;background:#f4f2ee;font-family:"DM Sans",sans-serif;}</style></head><body>');
  w.document.write(target.outerHTML);
  w.document.write('</body></html>');
  w.document.close();
  w.focus();
  setTimeout(function() { w.print(); }, 600);
}

async function downloadCardPng() {
  var target = currentFormat === 'card'
    ? document.getElementById('cardContainer')
    : document.querySelector('.standee-wrapper');
  if (!target) return;
  // For card: capture front (un-flipped) — temporarily remove flipped class
  var wasFlipped = target.classList.contains('flipped');
  if (wasFlipped) target.classList.remove('flipped');
  toast('Preparing download…');
  var canvas = await html2canvas(target, { scale: 3, useCORS: true, backgroundColor: null });
  if (wasFlipped) target.classList.add('flipped');
  var link = document.createElement('a');
  link.download = currentFormat === 'card' ? 'visiting-card.png' : 'standee.png';
  link.href = canvas.toDataURL('image/png');
  link.click();
}

// ── ADD NEW SECTION MODAL ─────────────────────────────────────────────────────
var currentSectionType = null;

function selectSectionType(type) {
  currentSectionType = type;
  document.getElementById('sectionTypeSelection').style.display = 'none';
  ['text','photo','video','document'].forEach(function(t) {
    document.getElementById(t + 'SectionForm').style.display = 'none';
  });
  document.getElementById(type + 'SectionForm').style.display = 'block';
  document.getElementById('backToTypesBtn').style.display = 'inline-flex';
  document.getElementById('addSectionBtn').textContent =
    'Add ' + type.charAt(0).toUpperCase() + type.slice(1);
}

function backToSectionTypes() {
  currentSectionType = null;
  document.getElementById('sectionTypeSelection').style.display = 'grid';
  ['text','photo','video','document'].forEach(function(t) {
    document.getElementById(t + 'SectionForm').style.display = 'none';
  });
  document.getElementById('backToTypesBtn').style.display = 'none';
  document.getElementById('addSectionBtn').textContent = 'Add Section';
}

function resetAddSectionModal_() {
  currentSectionType = null;
  ['textSectionTitle','textSectionContent',
   'photoSectionTitle','videoSectionTitle','docSectionTitle'].forEach(function(id) {
    var el = document.getElementById(id);
    if (el) el.value = '';
  });
  // Reset photo upload zone
  var pz = document.getElementById('photoUploadZone');
  if (pz) {
    pz.style.borderStyle = 'dashed';
    pz.style.borderColor = '#e0e0e0';
    pz.style.padding = '28px 16px';
    pz.innerHTML = '<i class="bi bi-cloud-upload" style="font-size:36px;color:var(--primary);display:block;margin-bottom:8px;"></i>' +
      '<div style="font-size:14px;font-weight:600;">Click to upload photos</div>' +
      '<div style="font-size:12px;color:var(--text-muted);margin-top:4px;">JPG, PNG, WebP — max 5 MB each · multiple allowed</div>';
  }
  var photoList = document.getElementById('photoSectionPreviewList');
  if (photoList) photoList.innerHTML = '';
  var pi = document.getElementById('photoSectionInput');
  if (pi) pi.value = '';
  // Reset doc upload zone
  var dz = document.getElementById('docUploadZone');
  if (dz) {
    dz.style.borderStyle = 'dashed';
    dz.style.borderColor = '#e0e0e0';
    dz.style.padding = '28px 16px';
    dz.innerHTML = '<i class="bi bi-file-earmark-arrow-up" style="font-size:36px;color:var(--primary);display:block;margin-bottom:8px;"></i>' +
      '<div style="font-size:14px;font-weight:600;">Click to upload documents</div>' +
      '<div style="font-size:12px;color:var(--text-muted);margin-top:4px;">PDF, Word, Excel — max 20 MB each · multiple allowed</div>';
  }
  var docList = document.getElementById('docSectionPreviewList');
  if (docList) docList.innerHTML = '';
  var di = document.getElementById('docSectionInput');
  if (di) di.value = '';
  // Reset video URL rows to single row
  vidRowCount = 1;
  var vrows = document.getElementById('videoUrlRows');
  if (vrows) {
    vrows.innerHTML =
      '<div class="cs-inline-add-row" style="display:flex;gap:8px;margin-bottom:8px;" id="vidRow0">' +
        '<input type="url" class="form-inp" name="vidUrl0" style="flex:1;margin-bottom:0;" placeholder="https://youtube.com/watch?v=…">' +
        '<button type="button" style="width:36px;height:42px;border:none;border-radius:8px;background:#f0f0f0;cursor:pointer;color:#999;flex-shrink:0;" onclick="removeVidRow(this)">' +
          '<i class="bi bi-x-lg"></i></button>' +
      '</div>';
  }
  backToSectionTypes();
}

// Multiple photo preview (thumbnail chips)
function handlePhotosPreview(input) {
  var list = document.getElementById('photoSectionPreviewList');
  if (!list) return;
  list.innerHTML = '';
  var files = Array.from(input.files);
  if (files.length > 0) {
    var pz = document.getElementById('photoUploadZone');
    if (pz) {
      pz.style.borderStyle = 'solid';
      pz.style.borderColor = 'var(--primary)';
      pz.style.padding = '12px 16px';
      pz.innerHTML = '<i class="bi bi-check-circle-fill" style="color:var(--secondary);font-size:24px;display:block;margin-bottom:4px;"></i>' +
        '<div style="font-size:14px;font-weight:600;">' + files.length + ' photo' + (files.length > 1 ? 's' : '') + ' selected</div>' +
        '<div style="font-size:12px;color:var(--text-muted);margin-top:2px;">Click to change</div>';
    }
  }
  files.forEach(function(f) {
    var reader = new FileReader();
    reader.onload = function(e) {
      var chip = document.createElement('div');
      chip.style.cssText = 'width:56px;height:56px;border-radius:8px;overflow:hidden;border:2px solid var(--primary);flex-shrink:0;';
      chip.innerHTML = '<img src="'+e.target.result+'" style="width:100%;height:100%;object-fit:cover;">';
      list.appendChild(chip);
    };
    reader.readAsDataURL(f);
  });
}

// Multiple document preview (filename chips)
function handleDocsPreview(input) {
  var list = document.getElementById('docSectionPreviewList');
  if (!list) return;
  list.innerHTML = '';
  var files = Array.from(input.files);
  if (files.length > 0) {
    var dz = document.getElementById('docUploadZone');
    if (dz) {
      dz.style.borderStyle = 'solid';
      dz.style.borderColor = 'var(--primary)';
      dz.style.padding = '12px 16px';
      dz.innerHTML = '<i class="bi bi-check-circle-fill" style="color:var(--secondary);font-size:24px;display:block;margin-bottom:4px;"></i>' +
        '<div style="font-size:14px;font-weight:600;">' + files.length + ' file' + (files.length > 1 ? 's' : '') + ' selected</div>' +
        '<div style="font-size:12px;color:var(--text-muted);margin-top:2px;">Click to change</div>';
    }
  }
  files.forEach(function(f) {
    var item = document.createElement('div');
    item.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 10px;background:#fafafa;border-radius:8px;border:1px solid #e8e8e8;margin-bottom:4px;';
    item.innerHTML = '<i class="bi bi-file-earmark-pdf" style="color:var(--primary);font-size:16px;flex-shrink:0;"></i>' +
                     '<span style="font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + escHtml(f.name) + '</span>';
    list.appendChild(item);
  });
}

// Video URL row helpers
var vidRowCount = 1;
function addVidRow() {
  var rows = document.getElementById('videoUrlRows');
  if (!rows) return;
  var idx = vidRowCount++;
  var row = document.createElement('div');
  row.className = 'cs-inline-add-row';
  row.id = 'vidRow' + idx;
  row.style.cssText = 'display:flex;gap:8px;margin-bottom:8px;';
  row.innerHTML =
    '<input type="url" class="form-inp" name="vidUrl'+idx+'" style="flex:1;margin-bottom:0;" placeholder="https://youtube.com/watch?v=…">' +
    '<button type="button" style="width:36px;height:42px;border:none;border-radius:8px;background:#f0f0f0;cursor:pointer;color:#999;flex-shrink:0;" onclick="removeVidRow(this)">' +
      '<i class="bi bi-x-lg"></i></button>';
  rows.appendChild(row);
}
function removeVidRow(btn) {
  var rows = document.getElementById('videoUrlRows');
  if (rows && rows.querySelectorAll('.cs-inline-add-row').length > 1) {
    btn.closest('.cs-inline-add-row').remove();
  } else {
    // Keep at least one row, just clear the value
    var inp = btn.previousElementSibling;
    if (inp) inp.value = '';
  }
}

async function submitAddSection() {
  if (!currentSectionType) { toast('Please select a section type.', true); return; }
  var type = currentSectionType;
  var btn  = document.getElementById('addSectionBtn');
  btn.disabled = true; btn.textContent = 'Saving…';

  var fd = new FormData();
  fd.append('section_type', type);

  if (type === 'text') {
    var title   = document.getElementById('textSectionTitle').value.trim();
    var content = document.getElementById('textSectionContent').value.trim();
    if (!title)   { toast('Section title is required.',  true); btn.disabled = false; btn.textContent = 'Add Text'; return; }
    if (!content) { toast('Please enter section content.', true); btn.disabled = false; btn.textContent = 'Add Text'; return; }
    fd.append('title', title);
    fd.append('content', content);

  } else if (type === 'photo') {
    var pTitle = document.getElementById('photoSectionTitle').value.trim();
    var pFiles = document.getElementById('photoSectionInput').files;
    if (!pFiles || pFiles.length === 0) { toast('Please select at least one photo.', true); btn.disabled = false; btn.textContent = 'Add Photo'; return; }
    if (pTitle) fd.append('title', pTitle);
    for (var i = 0; i < pFiles.length; i++) {
      fd.append('photos[]', pFiles[i]);
    }

  } else if (type === 'video') {
    var vTitle = document.getElementById('videoSectionTitle').value.trim();
    // Collect all URL inputs from the dynamic rows
    var urlInputs = document.querySelectorAll('#videoUrlRows input[type="url"]');
    var hasUrl = false;
    urlInputs.forEach(function(inp) {
      var v = inp.value.trim();
      if (v) { fd.append('urls[]', v); hasUrl = true; }
    });
    if (!hasUrl) { toast('Please enter at least one video URL.', true); btn.disabled = false; btn.textContent = 'Add Video'; return; }
    if (vTitle) fd.append('title', vTitle);

  } else if (type === 'document') {
    var dTitle = document.getElementById('docSectionTitle').value.trim();
    var dFiles = document.getElementById('docSectionInput').files;
    if (!dFiles || dFiles.length === 0) { toast('Please select at least one document.', true); btn.disabled = false; btn.textContent = 'Add Document'; return; }
    if (dTitle) fd.append('title', dTitle);
    for (var i = 0; i < dFiles.length; i++) {
      fd.append('documents[]', dFiles[i]);
    }
  }

  var res = await ajaxPost('<?= site_url('member/profile/add-section') ?>', fd);
  btn.disabled = false;

  if (res.success) {
    bootstrap.Modal.getInstance(document.getElementById('addSectionModal')).hide();
    resetAddSectionModal_();
    insertCustomSectionCard(res);
    toast(res.message || 'Section added!');
  } else {
    toast(res.message || 'Failed to add section.', true);
    btn.textContent = 'Add ' + type.charAt(0).toUpperCase() + type.slice(1);
  }
}

// ── Build & insert a custom section card from server response ─────────────────
function insertCustomSectionCard(s) {
  var anchor = document.getElementById('customSectionsEnd');
  var html   = buildCustomSectionHTML(s);
  if (anchor) {
    anchor.insertAdjacentHTML('beforebegin', html);
  } else {
    document.getElementById('appShell').insertAdjacentHTML('beforeend', html);
  }
}

function buildCustomSectionHTML(s) {
  var iconMap = {
    text: 'bi-file-text', photo: 'bi-image',
    video: 'bi-play-circle-fill', document: 'bi-file-earmark-pdf'
  };
  var icon = iconMap[s.type] || 'bi-puzzle';

  // data-* attributes for edit button (title + content for text)
  var dataAttrs = 'data-sec-id="' + s.id + '" data-sec-type="' + escAttr(s.type) + '" data-sec-title="' + escAttr(s.title) + '"';
  if (s.type === 'text') dataAttrs += ' data-sec-content="' + escAttr(s.content || '') + '"';

  var body = buildSectionBody(s);

  return '<div class="section-card" id="custom-section-' + s.id + '">' +
    '<div class="section-header">' +
      '<div class="section-title"><i class="bi ' + icon + '"></i> ' + escHtml(s.title) + '</div>' +
      '<div style="display:flex;gap:6px;flex-shrink:0;">' +
        '<button class="edit-btn cs-edit-btn" ' + dataAttrs + ' onclick="openEditSectionModal(this)" title="Edit section">' +
          '<i class="bi bi-pencil-fill"></i></button>' +
        '<button class="edit-btn" style="background:#dc3545;" ' +
          'onclick="deleteCustomSection(' + s.id + ')" title="Delete section">' +
          '<i class="bi bi-trash"></i></button>' +
      '</div>' +
    '</div>' +
    '<div class="cs-body">' + body + '</div>' +
  '</div>';
}

function buildSectionBody(s) {
  var items = s.items || [];

  // ── Text ────────────────────────────────────────────────────────────────────
  if (s.type === 'text') {
    return '<div class="about-text expanded" style="display:block;-webkit-line-clamp:unset;overflow:visible;">' +
           nl2brEsc(s.content || '') + '</div>';
  }

  // ── Photo ───────────────────────────────────────────────────────────────────
  if (s.type === 'photo') {
    var photoSlides = '';
    items.forEach(function(item, idx) {
      photoSlides +=
        '<div class="cs-car-photo-item" id="sitem-' + item.id + '" style="display:' + (idx === 0 ? 'block' : 'none') + ';">' +
          '<img src="' + escAttr(item.url) + '" alt="photo" loading="lazy" style="width:100%;height:240px;object-fit:cover;display:block;">' +
          '<button class="cs-item-del" title="Delete" onclick="deleteSectionPhoto(' + item.id + ',' + s.id + ')">' +
            '<i class="bi bi-x"></i></button>' +
        '</div>';
    });
    var n = items.length;
    var carHtml =
      '<div class="carousel-card" id="cs-photo-car-' + s.id + '" style="margin-bottom:10px;' + (n === 0 ? 'display:none;' : '') + '">' +
        '<span class="carousel-counter" id="cs-photo-count-' + s.id + '">' + (n > 0 ? '1 / ' + n : '') + '</span>' +
        photoSlides +
        '<button class="carousel-control-prev" id="cs-photo-prev-' + s.id + '" style="display:' + (n > 1 ? '' : 'none') + ';" ' +
          'onclick="csPhotoSlide(' + s.id + ', -1)"><i class="bi bi-chevron-left" style="filter:brightness(.3);"></i></button>' +
        '<button class="carousel-control-next" id="cs-photo-next-' + s.id + '" style="display:' + (n > 1 ? '' : 'none') + ';" ' +
          'onclick="csPhotoSlide(' + s.id + ', 1)"><i class="bi bi-chevron-right" style="filter:brightness(.3);"></i></button>' +
      '</div>';
    return carHtml +
      '<div class="cs-add-bar">' +
        '<button class="cs-add-btn" onclick="document.getElementById(\'sec-photo-input-' + s.id + '\').click()">' +
          '<i class="bi bi-plus-lg"></i> Add Photos</button>' +
      '</div>' +
      '<input type="file" id="sec-photo-input-' + s.id + '" accept="image/*" multiple style="display:none;" ' +
        'onchange="addSectionPhotos(' + s.id + ', this)">';
  }

  // ── Video ───────────────────────────────────────────────────────────────────
  if (s.type === 'video') {
    var vidSlides = '';
    items.forEach(function(item, idx) {
      vidSlides +=
        '<div class="cs-car-video-item" id="sitem-' + item.id + '" style="display:' + (idx === 0 ? 'block' : 'none') + ';">' +
          '<iframe class="cs-video-iframe" src="' + escAttr(item.embedUrl) + '" frameborder="0" ' +
            'allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" ' +
            'allowfullscreen loading="lazy"></iframe>' +
          '<div class="cs-video-foot">' +
            '<button class="cs-item-del" style="position:static;width:28px;height:28px;border-radius:6px;" title="Delete" ' +
              'onclick="deleteSectionVideo(' + item.id + ',' + s.id + ')">' +
              '<i class="bi bi-trash"></i></button>' +
          '</div>' +
        '</div>';
    });
    var nv = items.length;
    var carHtml2 =
      '<div class="carousel-card" id="cs-video-car-' + s.id + '" style="margin-bottom:10px;' + (nv === 0 ? 'display:none;' : '') + '">' +
        '<span class="carousel-counter" id="cs-video-count-' + s.id + '">' + (nv > 0 ? '1 / ' + nv : '') + '</span>' +
        '<div id="cs-videos-' + s.id + '">' + vidSlides + '</div>' +
        '<button class="carousel-control-prev" id="cs-video-prev-' + s.id + '" style="display:' + (nv > 1 ? '' : 'none') + ';" ' +
          'onclick="csVideoSlide(' + s.id + ', -1)"><i class="bi bi-chevron-left" style="filter:brightness(.3);"></i></button>' +
        '<button class="carousel-control-next" id="cs-video-next-' + s.id + '" style="display:' + (nv > 1 ? '' : 'none') + ';" ' +
          'onclick="csVideoSlide(' + s.id + ', 1)"><i class="bi bi-chevron-right" style="filter:brightness(.3);"></i></button>' +
      '</div>';
    return carHtml2 +
      '<div class="cs-inline-add" id="cs-vid-add-' + s.id + '">' +
        '<div class="cs-inline-add-row">' +
          '<input type="url" class="form-inp" id="cs-vid-url-' + s.id + '" placeholder="https://youtube.com/watch?v=…" style="flex:1;margin-bottom:0;">' +
          '<button class="cs-add-btn" style="border-style:solid;flex-shrink:0;" onclick="addSectionVideo(' + s.id + ')">' +
            '<i class="bi bi-plus-lg"></i> Add</button>' +
        '</div>' +
      '</div>' +
      '<div class="cs-add-bar">' +
        '<button class="cs-add-btn" onclick="toggleCsVidAdd(' + s.id + ')">' +
          '<i class="bi bi-plus-lg"></i> Add Video</button>' +
      '</div>';
  }

  // ── Document ─────────────────────────────────────────────────────────────────
  if (s.type === 'document') {
    var docRows = '';
    items.forEach(function(item) {
      docRows += '<div class="cs-doc-row" id="sitem-' + item.id + '">' +
        '<div class="doc-icon"><i class="bi bi-file-earmark-pdf"></i></div>' +
        '<div style="flex:1;min-width:0;">' +
          '<div class="doc-name" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + escHtml(item.filename || 'Document') + '</div>' +
          '<div class="doc-size">' + escHtml(item.size || '') + '</div>' +
        '</div>' +
        (item.url ? '<a href="' + escAttr(item.url) + '" target="_blank" class="doc-del-btn" style="color:var(--secondary);background:rgba(0,168,84,.1);" title="Download"><i class="bi bi-download"></i></a>' : '') +
        '<button class="doc-del-btn" title="Delete" onclick="deleteSectionItem(' + item.id + ',\'sitem-' + item.id + '\')">' +
          '<i class="bi bi-trash"></i></button>' +
      '</div>';
    });
    return '<div id="cs-docs-' + s.id + '">' + docRows + '</div>' +
      '<div class="cs-add-bar">' +
        '<button class="cs-add-btn" onclick="document.getElementById(\'sec-doc-input-' + s.id + '\').click()">' +
          '<i class="bi bi-plus-lg"></i> Add Documents</button>' +
      '</div>' +
      '<input type="file" id="sec-doc-input-' + s.id + '" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt" multiple style="display:none;" ' +
        'onchange="addSectionDocuments(' + s.id + ', this)">';
  }
  return '';
}

// ── Delete a custom section ───────────────────────────────────────────────────
async function deleteCustomSection(id) {
  if (!confirm('Delete this section? This cannot be undone.')) return;
  var res = await ajaxPost('<?= site_url('member/profile/delete-section/') ?>' + id, {});
  if (res.success) {
    var el = document.getElementById('custom-section-' + id);
    if (el) {
      el.style.transition = 'opacity .25s';
      el.style.opacity    = '0';
      setTimeout(function() { el.remove(); }, 260);
    }
    toast('Section deleted.');
  } else {
    toast(res.message || 'Delete failed.', true);
  }
}

// ── Section Item Management ───────────────────────────────────────────────────

var ADD_ITEM_URL    = '<?= site_url('member/profile/add-section-item/') ?>';
var DEL_ITEM_URL    = '<?= site_url('member/profile/delete-section-item/') ?>';

// Add multiple photos to an existing section
async function addSectionPhotos(secId, input) {
  if (!input.files || !input.files.length) return;
  var files = Array.from(input.files);
  var fd    = new FormData();
  files.forEach(function(f) { fd.append('photos[]', f); });
  toast('Uploading ' + files.length + ' photo(s)…');

  var res = await ajaxPost(ADD_ITEM_URL + secId, fd);
  input.value = '';

  if (res.success && res.items) {
    // Ensure carousel container exists
    var car = document.getElementById('cs-photo-car-' + secId);
    if (!car) {
      car = document.createElement('div');
      car.className = 'carousel-card';
      car.id = 'cs-photo-car-' + secId;
      car.style.marginBottom = '10px';
      car.innerHTML =
        '<span class="carousel-counter" id="cs-photo-count-' + secId + '"></span>' +
        '<button class="carousel-control-prev" id="cs-photo-prev-' + secId + '" style="display:none;" ' +
          'onclick="csPhotoSlide(' + secId + ',-1)"><i class="bi bi-chevron-left" style="filter:brightness(.3);"></i></button>' +
        '<button class="carousel-control-next" id="cs-photo-next-' + secId + '" style="display:none;" ' +
          'onclick="csPhotoSlide(' + secId + ',1)"><i class="bi bi-chevron-right" style="filter:brightness(.3);"></i></button>';
      var body = document.querySelector('#custom-section-' + secId + ' .cs-body');
      if (body) body.insertBefore(car, body.firstChild);
    }
    car.style.display = '';
    // Insert new items before the prev/next buttons
    var prevBtn = document.getElementById('cs-photo-prev-' + secId);
    res.items.forEach(function(item) {
      var div = document.createElement('div');
      div.className = 'cs-car-photo-item';
      div.id = 'sitem-' + item.id;
      div.style.display = 'none';
      div.innerHTML =
        '<img src="' + escAttr(item.url) + '" alt="photo" loading="lazy" style="width:100%;height:240px;object-fit:cover;display:block;">' +
        '<button class="cs-item-del" title="Delete" onclick="deleteSectionPhoto(' + item.id + ',' + secId + ')"><i class="bi bi-x"></i></button>';
      if (prevBtn) car.insertBefore(div, prevBtn);
      else car.appendChild(div);
    });
    csPhotoRefresh(secId, true); // navigate to the last (newest) photo
    toast(res.message || 'Photos added!');
  } else {
    toast(res.message || 'Upload failed.', true);
  }
}

// Add a single video URL to an existing section (from inline form)
async function addSectionVideo(secId) {
  var inp = document.getElementById('cs-vid-url-' + secId);
  var url = inp ? inp.value.trim() : '';
  if (!url) { toast('Please enter a video URL.', true); return; }
  var fd = new FormData();
  fd.append('urls[]', url);

  var res = await ajaxPost(ADD_ITEM_URL + secId, fd);

  if (res.success && res.items && res.items[0]) {
    var item = res.items[0];
    var car  = document.getElementById('cs-video-car-' + secId);
    var list = document.getElementById('cs-videos-' + secId);
    if (car) car.style.display = '';
    if (list) {
      var div = document.createElement('div');
      div.className = 'cs-car-video-item';
      div.id = 'sitem-' + item.id;
      div.style.display = 'none';
      div.innerHTML =
        '<iframe class="cs-video-iframe" src="' + escAttr(item.embedUrl) + '" frameborder="0" ' +
          'allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" ' +
          'allowfullscreen loading="lazy"></iframe>' +
        '<div class="cs-video-foot">' +
          '<button class="cs-item-del" style="position:static;width:28px;height:28px;border-radius:6px;" title="Delete" ' +
            'onclick="deleteSectionVideo(' + item.id + ',' + secId + ')">' +
            '<i class="bi bi-trash"></i></button>' +
        '</div>';
      list.appendChild(div);
    }
    if (inp) inp.value = '';
    var addBox = document.getElementById('cs-vid-add-' + secId);
    if (addBox) addBox.classList.remove('open');
    csVideoRefresh(secId, true); // navigate to the last (newest) video
    toast('Video added!');
  } else {
    toast(res.message || 'Failed to add video.', true);
  }
}

// Toggle the inline video-add form
function toggleCsVidAdd(secId) {
  var box = document.getElementById('cs-vid-add-' + secId);
  if (box) box.classList.toggle('open');
}

// ── Custom-section PHOTO carousel ────────────────────────────────────────────
var csPhotoIdx = {};

function csPhotoSlide(secId, dir) {
  var car   = document.getElementById('cs-photo-car-' + secId);
  if (!car) return;
  var items = car.querySelectorAll('.cs-car-photo-item');
  var n     = items.length;
  if (!n) return;
  var cur = ((csPhotoIdx[secId] || 0) + dir + n) % n;
  csPhotoIdx[secId] = cur;
  items.forEach(function(el, i) { el.style.display = i === cur ? 'block' : 'none'; });
  var ctr = document.getElementById('cs-photo-count-' + secId);
  if (ctr) ctr.textContent = (cur + 1) + ' / ' + n;
}

function csPhotoRefresh(secId, gotoLast) {
  var car   = document.getElementById('cs-photo-car-' + secId);
  if (!car) return;
  var items = car.querySelectorAll('.cs-car-photo-item');
  var n     = items.length;
  if (n === 0) { car.style.display = 'none'; return; }
  var cur = gotoLast
    ? n - 1
    : Math.min(csPhotoIdx[secId] || 0, n - 1);
  if (cur < 0) cur = 0;
  csPhotoIdx[secId] = cur;
  items.forEach(function(el, i) { el.style.display = i === cur ? 'block' : 'none'; });
  var ctr  = document.getElementById('cs-photo-count-' + secId);
  if (ctr) ctr.textContent = (cur + 1) + ' / ' + n;
  var prev = document.getElementById('cs-photo-prev-' + secId);
  var next = document.getElementById('cs-photo-next-' + secId);
  if (prev) prev.style.display = n > 1 ? '' : 'none';
  if (next) next.style.display = n > 1 ? '' : 'none';
}

function deleteSectionPhoto(itemId, secId) {
  if (!confirm('Delete this photo?')) return;
  ajaxPost(DEL_ITEM_URL + itemId, {}).then(function(res) {
    if (res.success) {
      var el = document.getElementById('sitem-' + itemId);
      if (el) el.remove();
      csPhotoRefresh(secId, false);
      toast('Photo deleted.');
    } else {
      toast(res.message || 'Delete failed.', true);
    }
  });
}

// ── Custom-section VIDEO carousel ────────────────────────────────────────────
var csVideoIdx = {};

function csVideoSlide(secId, dir) {
  var list  = document.getElementById('cs-videos-' + secId);
  if (!list) return;
  var items = list.querySelectorAll('.cs-car-video-item');
  var n     = items.length;
  if (!n) return;
  var cur = ((csVideoIdx[secId] || 0) + dir + n) % n;
  csVideoIdx[secId] = cur;
  items.forEach(function(el, i) { el.style.display = i === cur ? 'block' : 'none'; });
  var ctr = document.getElementById('cs-video-count-' + secId);
  if (ctr) ctr.textContent = (cur + 1) + ' / ' + n;
}

function csVideoRefresh(secId, gotoLast) {
  var list  = document.getElementById('cs-videos-' + secId);
  var car   = document.getElementById('cs-video-car-' + secId);
  if (!list) return;
  var items = list.querySelectorAll('.cs-car-video-item');
  var n     = items.length;
  if (n === 0) { if (car) car.style.display = 'none'; return; }
  var cur = gotoLast
    ? n - 1
    : Math.min(csVideoIdx[secId] || 0, n - 1);
  if (cur < 0) cur = 0;
  csVideoIdx[secId] = cur;
  items.forEach(function(el, i) { el.style.display = i === cur ? 'block' : 'none'; });
  var ctr  = document.getElementById('cs-video-count-' + secId);
  if (ctr) ctr.textContent = (cur + 1) + ' / ' + n;
  var prev = document.getElementById('cs-video-prev-' + secId);
  var next = document.getElementById('cs-video-next-' + secId);
  if (prev) prev.style.display = n > 1 ? '' : 'none';
  if (next) next.style.display = n > 1 ? '' : 'none';
}

function deleteSectionVideo(itemId, secId) {
  if (!confirm('Delete this video?')) return;
  ajaxPost(DEL_ITEM_URL + itemId, {}).then(function(res) {
    if (res.success) {
      var el = document.getElementById('sitem-' + itemId);
      if (el) el.remove();
      csVideoRefresh(secId, false);
      toast('Video deleted.');
    } else {
      toast(res.message || 'Delete failed.', true);
    }
  });
}

// Add multiple documents to an existing section
async function addSectionDocuments(secId, input) {
  if (!input.files || !input.files.length) return;
  var files = Array.from(input.files);
  var fd    = new FormData();
  files.forEach(function(f) { fd.append('documents[]', f); });
  toast('Uploading ' + files.length + ' document(s)…');

  var res = await ajaxPost(ADD_ITEM_URL + secId, fd);
  input.value = '';

  if (res.success && res.items) {
    var list = document.getElementById('cs-docs-' + secId);
    if (list) {
      res.items.forEach(function(item) {
        var div = document.createElement('div');
        div.className = 'cs-doc-row';
        div.id = 'sitem-' + item.id;
        div.innerHTML =
          '<div class="doc-icon"><i class="bi bi-file-earmark-pdf"></i></div>' +
          '<div style="flex:1;min-width:0;">' +
            '<div class="doc-name" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + escHtml(item.filename || 'Document') + '</div>' +
            '<div class="doc-size">' + escHtml(item.size || '') + '</div>' +
          '</div>' +
          '<a href="' + escAttr(item.url) + '" target="_blank" class="doc-del-btn" style="color:var(--secondary);background:rgba(0,168,84,.1);" title="Download"><i class="bi bi-download"></i></a>' +
          '<button class="doc-del-btn" title="Delete" onclick="deleteSectionItem(' + item.id + ',\'sitem-' + item.id + '\')">' +
            '<i class="bi bi-trash"></i></button>';
        list.appendChild(div);
      });
    }
    toast(res.message || 'Documents added!');
  } else {
    toast(res.message || 'Upload failed.', true);
  }
}

// Delete a single section item
async function deleteSectionItem(itemId, domId) {
  if (!confirm('Delete this item?')) return;
  var res = await ajaxPost(DEL_ITEM_URL + itemId, {});
  if (res.success) {
    var el = document.getElementById(domId);
    if (el) {
      el.style.transition = 'opacity .2s';
      el.style.opacity    = '0';
      setTimeout(function() { el.remove(); }, 220);
    }
    toast('Item deleted.');
  } else {
    toast(res.message || 'Delete failed.', true);
  }
}

// ── Edit Section Modal ────────────────────────────────────────────────────────

var EDIT_SEC_URL = '<?= site_url('member/profile/update-section/') ?>';

function openEditSectionModal(btn) {
  var id    = btn.getAttribute('data-sec-id');
  var type  = btn.getAttribute('data-sec-type');
  var title = btn.getAttribute('data-sec-title') || '';

  document.getElementById('editSecId').value    = id;
  document.getElementById('editSecType').value  = type;
  document.getElementById('editSecTitle').value = title;

  // Set modal heading
  var icons  = { text:'bi-file-text', photo:'bi-image', video:'bi-play-circle-fill', document:'bi-file-earmark-pdf' };
  var labels = { text:'Edit Text Section', photo:'Edit Photo Section', video:'Edit Video Section', document:'Edit Document Section' };
  var subs   = { text:'Update the title and content', photo:'Update the section title', video:'Update the section title', document:'Update the section title' };
  document.getElementById('editSecModalTitle').innerHTML =
    '<i class="bi ' + (icons[type]||'bi-puzzle') + '"></i> ' + (labels[type] || 'Edit Section');
  document.getElementById('editSecModalSubtitle').textContent = subs[type] || 'Update section';

  // Show text fields only for text type; show info note for others
  var textFields  = document.getElementById('editSecTextFields');
  var mediaNote   = document.getElementById('editSecMediaNote');
  if (type === 'text') {
    textFields.style.display = 'block';
    mediaNote.style.display  = 'none';
    document.getElementById('editSecContent').value = btn.getAttribute('data-sec-content') || '';
  } else {
    textFields.style.display = 'none';
    mediaNote.style.display  = 'block';
  }

  new bootstrap.Modal(document.getElementById('editSectionModal')).show();
}

function resetEditSectionModal() {
  document.getElementById('editSecTitle').value   = '';
  document.getElementById('editSecContent').value = '';
}

async function saveEditSection() {
  var id    = document.getElementById('editSecId').value;
  var type  = document.getElementById('editSecType').value;
  var title = document.getElementById('editSecTitle').value.trim();

  if (!title) { toast('Section title is required.', true); return; }

  var btn = document.getElementById('editSecSaveBtn');
  btn.disabled = true; btn.textContent = 'Saving…';

  var fd = new FormData();
  fd.append('title', title);

  if (type === 'text') {
    var content = document.getElementById('editSecContent').value.trim();
    if (!content) { toast('Content is required.', true); btn.disabled = false; btn.textContent = 'Save Changes'; return; }
    fd.append('content', content);
  }

  var res = await ajaxPost(EDIT_SEC_URL + id, fd);
  btn.disabled = false; btn.textContent = 'Save Changes';

  if (res.success) {
    bootstrap.Modal.getInstance(document.getElementById('editSectionModal')).hide();
    resetEditSectionModal();
    updateCustomSectionCard(res);
    toast(res.message || 'Section updated!');
  } else {
    toast(res.message || 'Update failed.', true);
  }
}

function updateCustomSectionCard(res) {
  var card = document.getElementById('custom-section-' + res.id);
  if (!card) return;

  var iconMap = { text:'bi-file-text', photo:'bi-image', video:'bi-play-circle-fill', document:'bi-file-earmark-pdf' };

  // 1. Update title in the card header
  var titleEl = card.querySelector('.section-title');
  if (titleEl) {
    titleEl.innerHTML = '<i class="bi ' + (iconMap[res.type]||'bi-puzzle') + '"></i> ' + escHtml(res.title);
  }

  // 2. For text sections, also rebuild body with new content
  if (res.type === 'text') {
    var bodyEl = card.querySelector('.cs-body');
    if (bodyEl) {
      bodyEl.innerHTML = buildSectionBody(res);
    }
  }

  // 3. Refresh data-* attributes on the edit button
  var editBtn = card.querySelector('.cs-edit-btn');
  if (editBtn) {
    editBtn.setAttribute('data-sec-title', res.title);
    if (res.type === 'text') editBtn.setAttribute('data-sec-content', res.content || '');
  }
}

// ── HTML escaping helpers ─────────────────────────────────────────────────────
function escHtml(str) {
  var d = document.createElement('div');
  d.textContent = String(str || '');
  return d.innerHTML;
}
function escAttr(str) {
  return String(str || '').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}
function nl2brEsc(str) {
  return escHtml(str).replace(/\n/g, '<br>');
}

// ── INIT ───────────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
  renderMenuThemes();

  // Side indicator updates when card is flipped
  var cardCont  = document.getElementById('cardContainer');
  var indicator = document.getElementById('sideIndicator');
  if (cardCont && indicator) {
    new MutationObserver(function() {
      indicator.textContent = cardCont.classList.contains('flipped') ? 'Back Side' : 'Front Side';
    }).observe(cardCont, { attributes: true, attributeFilter: ['class'] });
  }
});
</script>
</body>
</html>
