<script type="application/ld+json">
<%
  const _social = typeof org.social_links === 'string' ? JSON.parse(org.social_links || '{}') : (org.social_links || {});
  const _appUrl = process.env.APP_URL || 'https://biz2bizchamber.com';
  const _schema = {
    "@context": "https://schema.org",
    "@type": "LocalBusiness",
    "name": org.name,
    "url": org.website || (_appUrl + '/directory/' + org.slug),
    "description": org.short_description || org.description || '',
    "address": org.address ? {
      "@type": "PostalAddress",
      "streetAddress": org.address,
      "addressLocality": org.city || '',
      "addressRegion": org.state || '',
      "postalCode": org.zip || '',
      "addressCountry": org.country || 'US'
    } : undefined,
    "telephone": org.phone || undefined,
    "email": org.email || undefined,
    "image": org.logo ? (org.logo.startsWith('http') ? org.logo : _appUrl + org.logo) : undefined,
    "sameAs": [_social.linkedin, _social.facebook, _social.twitter, _social.instagram, _social.youtube].filter(Boolean),
    "aggregateRating": org.rating > 0 ? {
      "@type": "AggregateRating",
      "ratingValue": parseFloat(org.rating).toFixed(1),
      "reviewCount": org.review_count || 1
    } : undefined,
    "foundingDate": org.year_established ? String(org.year_established) : undefined,
    "numberOfEmployees": org.employee_count ? { "@type": "QuantitativeValue", "value": org.employee_count } : undefined
  };
  Object.keys(_schema).forEach(k => _schema[k] === undefined && delete _schema[k]);
  if (_schema.address) Object.keys(_schema.address).forEach(k => _schema.address[k] === undefined && delete _schema.address[k]);
%>
<%- JSON.stringify(_schema, null, 2) %>
</script>

<!-- Profile Hero -->
<section class="biz-profile-hero">
  <div class="container">
    <div class="biz-profile-hero-inner">
      <div class="biz-profile-logo-wrap">
        <% if (org.logo) { %>
          <img src="<%= org.logo %>" alt="<%= org.name %>" class="biz-profile-logo">
        <% } else { %>
          <div class="biz-profile-logo-placeholder"><%= org.name[0].toUpperCase() %></div>
        <% } %>
      </div>
      <div class="biz-profile-hero-info">
        <div class="biz-profile-hero-top">
          <h1><%= org.name %></h1>
          <span class="biz-verified-badge"><i class="bi bi-patch-check-fill"></i> Verified Member</span>
        </div>
        <div class="biz-profile-meta">
          <% if (org.category_name) { %><span><i class="bi bi-tag-fill"></i> <%= org.category_name %></span><% } %>
          <% if (org.city || org.state) { %><span><i class="bi bi-geo-alt-fill"></i> <%= [org.city, org.state].filter(Boolean).join(', ') %></span><% } %>
          <% if (org.year_established) { %><span><i class="bi bi-calendar3"></i> Est. <%= org.year_established %></span><% } %>
          <% if (org.employee_count) { %><span><i class="bi bi-people-fill"></i> <%= org.employee_count %> employees</span><% } %>
        </div>
        <% if (org.rating > 0) { %>
        <div class="biz-profile-rating">
          <% for(let i=1;i<=5;i++) { %><i class="bi bi-star<%= i <= Math.round(org.rating) ? '-fill' : (i - 0.5 <= org.rating ? '-half' : '') %>"></i><% } %>
          <strong><%= parseFloat(org.rating).toFixed(1) %></strong>
          <span>(<%= org.review_count || 0 %> reviews)</span>
        </div>
        <% } %>
      </div>
    </div>
  </div>
</section>

<!-- Breadcrumb -->
<div class="biz-breadcrumb">
  <div class="container">
    <a href="/">Home</a> <i class="bi bi-chevron-right"></i>
    <a href="/directory">Directory</a> <i class="bi bi-chevron-right"></i>
    <span><%= org.name %></span>
  </div>
</div>

<section class="section" style="padding-top:32px">
  <div class="container">
    <div class="biz-profile-grid">

      <!-- Main Content -->
      <div class="biz-profile-main">
        <% if (org.description) { %>
        <div class="biz-section-card">
          <h2>About <%= org.name %></h2>
          <div class="biz-description"><%- org.description.replace(/\n/g, '<br>') %></div>
        </div>
        <% } %>

        <!-- Services / Keywords -->
        <% if (org.keywords) { %>
        <div class="biz-section-card">
          <h2>Services & Specialties</h2>
          <div class="biz-tags">
            <% org.keywords.split(',').map(k => k.trim()).filter(Boolean).forEach(k => { %>
            <span class="biz-tag"><%= k %></span>
            <% }) %>
          </div>
        </div>
        <% } %>

        <!-- Reviews -->
        <div class="biz-section-card">
          <div class="biz-reviews-header">
            <h2>Customer Reviews</h2>
            <% if (org.rating > 0) { %>
            <div class="biz-rating-summary">
              <span class="biz-rating-big"><%= parseFloat(org.rating).toFixed(1) %></span>
              <div>
                <div class="biz-stars-row"><% for(let i=1;i<=5;i++) { %><i class="bi bi-star<%= i <= Math.round(org.rating) ? '-fill' : '' %>"></i><% } %></div>
                <span style="font-size:.8rem;color:#6b7280"><%= org.review_count || 0 %> reviews</span>
              </div>
            </div>
            <% } %>
          </div>

          <% if (reviews && reviews.length) { %>
          <div class="biz-reviews-list">
            <% reviews.forEach(r => { %>
            <div class="biz-review">
              <div class="biz-review-header">
                <div class="biz-review-avatar">
                  <% if (r.avatar) { %><img src="<%= r.avatar %>" alt=""><% } else { %><span><%= r.first_name[0] %></span><% } %>
                </div>
                <div class="biz-review-meta">
                  <strong><%= r.first_name %> <%= r.last_name %></strong>
                  <% if (r.reviewer_org) { %><span class="biz-review-org"><%= r.reviewer_org %></span><% } %>
                </div>
                <div class="biz-review-stars">
                  <% for(let i=1;i<=5;i++) { %><i class="bi bi-star<%= i <= r.rating ? '-fill' : '' %>"></i><% } %>
                </div>
              </div>
              <% if (r.title) { %><p class="biz-review-title">"<%= r.title %>"</p><% } %>
              <p class="biz-review-body"><%= r.content %></p>
            </div>
            <% }) %>
          </div>
          <% } else { %>
          <div class="biz-reviews-empty">
            <i class="bi bi-chat-square-heart"></i>
            <p>No reviews yet. Be the first to review this business.</p>
          </div>
          <% } %>

          <!-- Public review form -->
          <div class="biz-review-cta" id="reviewFormSection">
            <% if (currentUser) { %>
            <button class="btn btn-outline-primary btn-sm" onclick="toggleReviewForm()"><i class="bi bi-star-fill"></i> Write a Review</button>
            <% } else { %>
            <button class="btn btn-outline-primary btn-sm" onclick="toggleReviewForm()"><i class="bi bi-star-fill"></i> Write a Review</button>
            <p style="font-size:.78rem;color:#9ca3af;margin-top:6px">No account needed. Reviews are moderated before publishing.</p>
            <% } %>
          </div>

          <div id="reviewForm" style="display:none;margin-top:20px;padding:20px;background:#f9fafb;border-radius:12px;border:1.5px solid #e5e7eb">
            <h4 style="margin:0 0 16px">Write Your Review</h4>
            <div style="margin-bottom:12px">
              <label style="font-size:.85rem;font-weight:600;display:block;margin-bottom:6px">Rating *</label>
              <div class="star-picker" id="starPicker">
                <% for(let i=1;i<=5;i++){%><i class="bi bi-star" data-val="<%= i %>" style="font-size:1.5rem;cursor:pointer;color:#d1d5db" onclick="setRating(<%= i %>)"></i><%}%>
              </div>
              <input type="hidden" id="reviewRating" value="">
            </div>
            <% if (!currentUser) { %>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px">
              <div><label style="font-size:.8rem;font-weight:600;display:block;margin-bottom:4px">Your Name *</label><input type="text" id="reviewName" placeholder="Jane Smith" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:7px;font-size:.875rem;box-sizing:border-box"></div>
              <div><label style="font-size:.8rem;font-weight:600;display:block;margin-bottom:4px">Email (not shown) *</label><input type="email" id="reviewEmail" placeholder="jane@email.com" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:7px;font-size:.875rem;box-sizing:border-box"></div>
            </div>
            <div style="margin-bottom:10px"><label style="font-size:.8rem;font-weight:600;display:block;margin-bottom:4px">Company (optional)</label><input type="text" id="reviewCompany" placeholder="Your business name" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:7px;font-size:.875rem;box-sizing:border-box"></div>
            <% } %>
            <div style="margin-bottom:10px"><label style="font-size:.8rem;font-weight:600;display:block;margin-bottom:4px">Headline (optional)</label><input type="text" id="reviewTitle" placeholder="e.g., Excellent service!" style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:7px;font-size:.875rem;box-sizing:border-box"></div>
            <div style="margin-bottom:14px"><label style="font-size:.8rem;font-weight:600;display:block;margin-bottom:4px">Review *</label><textarea id="reviewContent" rows="4" placeholder="Share your experience with this business..." style="width:100%;padding:8px 10px;border:1.5px solid #e5e7eb;border-radius:7px;font-size:.875rem;resize:vertical;box-sizing:border-box"></textarea></div>
            <div id="reviewError" style="display:none;color:#dc2626;font-size:.8rem;margin-bottom:8px"></div>
            <div style="display:flex;gap:10px">
              <button class="btn btn-primary btn-sm" onclick="submitReview('<%= org.slug %>')"><i class="bi bi-send-fill"></i> Submit Review</button>
              <button class="btn btn-ghost btn-sm" onclick="document.getElementById('reviewForm').style.display='none'">Cancel</button>
            </div>
          </div>
        </div>
      </div>

      <!-- Sidebar -->
      <aside class="biz-profile-sidebar">
        <!-- Contact Info -->
        <div class="biz-sidebar-card">
          <h3>Contact Information</h3>
          <ul class="biz-contact-list">
            <% if (org.website) { %>
            <li>
              <i class="bi bi-globe2"></i>
              <a href="<%= org.website %>" target="_blank" rel="noopener"><%= org.website.replace(/^https?:\/\//, '') %></a>
            </li>
            <% } %>
            <% if (org.phone) { %>
            <li><i class="bi bi-telephone-fill"></i><a href="tel:<%= org.phone %>"><%= org.phone %></a></li>
            <% } %>
            <% if (org.email) { %>
            <li><i class="bi bi-envelope-fill"></i><a href="mailto:<%= org.email %>"><%= org.email %></a></li>
            <% } %>
            <% if (org.address) { %>
            <li>
              <i class="bi bi-geo-alt-fill"></i>
              <span><%= org.address %><% if (org.city) { %>, <%= org.city %><% } %><% if (org.state) { %>, <%= org.state %><% } %> <% if (org.zip) { %><%= org.zip %><% } %></span>
            </li>
            <% } %>
          </ul>
        </div>

        <!-- Social Links -->
        <% const social = typeof org.social_links === 'string' ? JSON.parse(org.social_links || '{}') : (org.social_links || {}); %>
        <% if (social.linkedin || social.facebook || social.twitter || social.instagram) { %>
        <div class="biz-sidebar-card">
          <h3>Follow on Social</h3>
          <div class="biz-social-links">
            <% if (social.linkedin) { %><a href="<%= social.linkedin %>" target="_blank" rel="noopener" class="biz-social-btn biz-social-linkedin"><i class="bi bi-linkedin"></i></a><% } %>
            <% if (social.facebook) { %><a href="<%= social.facebook %>" target="_blank" rel="noopener" class="biz-social-btn biz-social-facebook"><i class="bi bi-facebook"></i></a><% } %>
            <% if (social.twitter) { %><a href="<%= social.twitter %>" target="_blank" rel="noopener" class="biz-social-btn biz-social-twitter"><i class="bi bi-twitter-x"></i></a><% } %>
            <% if (social.instagram) { %><a href="<%= social.instagram %>" target="_blank" rel="noopener" class="biz-social-btn biz-social-instagram"><i class="bi bi-instagram"></i></a><% } %>
          </div>
        </div>
        <% } %>

        <!-- CTA -->
        <div class="biz-sidebar-card biz-sidebar-cta">
          <h3>Are you this business?</h3>
          <p>Claim your profile, respond to reviews, and access all member tools.</p>
          <a href="/login" class="btn btn-primary btn-sm btn-block">Log In to Manage</a>
          <a href="/register" class="btn btn-outline-primary btn-sm btn-block" style="margin-top:8px">Join Biz2Biz Chamber</a>
        </div>

        <!-- Back to directory -->
        <a href="/directory" class="biz-back-link"><i class="bi bi-arrow-left"></i> Back to Directory</a>
      </aside>
    </div>
  </div>
</section>

<script>
let _selectedRating = 0;
function toggleReviewForm() {
  const f = document.getElementById('reviewForm');
  f.style.display = f.style.display === 'none' ? 'block' : 'none';
  if (f.style.display === 'block') f.scrollIntoView({ behavior: 'smooth' });
}
function setRating(val) {
  _selectedRating = val;
  document.getElementById('reviewRating').value = val;
  document.querySelectorAll('#starPicker i').forEach((s, i) => {
    s.className = i < val ? 'bi bi-star-fill' : 'bi bi-star';
    s.style.color = i < val ? '#f59e0b' : '#d1d5db';
  });
}
async function submitReview(slug) {
  const errEl = document.getElementById('reviewError');
  errEl.style.display = 'none';
  const body = {
    rating: _selectedRating,
    title: document.getElementById('reviewTitle')?.value.trim() || '',
    content: document.getElementById('reviewContent')?.value.trim() || '',
    reviewer_name: document.getElementById('reviewName')?.value.trim() || '',
    reviewer_email: document.getElementById('reviewEmail')?.value.trim() || '',
    reviewer_company: document.getElementById('reviewCompany')?.value.trim() || ''
  };
  const res  = await fetch(`/directory/${slug}/review`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
  const data = await res.json();
  if (data.success) {
    document.getElementById('reviewForm').innerHTML = `<div style="text-align:center;padding:20px"><i class="bi bi-check-circle-fill" style="font-size:2rem;color:#16a34a;display:block;margin-bottom:8px"></i><p style="font-weight:600;color:#16a34a">${data.message}</p></div>`;
  } else {
    errEl.textContent = data.error || 'Submission failed.';
    errEl.style.display = 'block';
  }
}
</script>
