// ListingPage.jsx — Individual farm detail view

const ListingPage = ({ navigate, listingId }) => {
  const listing = window.LISTINGS_DATA.find(l => l.id === listingId);
  const [reviewText, setReviewText] = React.useState('');
  const [reviewRating, setReviewRating] = React.useState(5);
  const [reviewSubmitted, setReviewSubmitted] = React.useState(false);
  const [hoveredStar, setHoveredStar] = React.useState(null);
  const [activePhoto, setActivePhoto] = React.useState(null);

  if (!listing) {
    return (
      <div style={{ paddingTop: 120, textAlign: 'center', minHeight: '60vh' }}>
        <div style={{ fontSize: 48, marginBottom: 16 }}>🌾</div>
        <h2 style={{ fontFamily: 'Playfair Display, serif', fontSize: 28, color: 'var(--bark)', marginBottom: 12 }}>Farm not found</h2>
        <button onClick={() => navigate('browse')} style={{
          background: 'var(--orange)', color: '#fff', border: 'none',
          borderRadius: 8, padding: '12px 24px', fontSize: 15,
          fontFamily: 'Source Serif 4, serif', fontWeight: 600, cursor: 'pointer',
        }}>Back to Directory</button>
      </div>
    );
  }

  const colors = CATEGORY_COLORS[listing.category] || CATEGORY_COLORS['Pumpkin Patch'];
  const similar = window.LISTINGS_DATA
    .filter(l => l.id !== listing.id && l.category === listing.category)
    .slice(0, 3);

  const handleReviewSubmit = (e) => {
    e.preventDefault();
    if (reviewText.trim()) setReviewSubmitted(true);
  };

  return (
    <div style={{ paddingTop: 68, minHeight: '100vh' }}>

      {/* ── BACK BUTTON ── */}
      <div style={{
        maxWidth: 1280, margin: '0 auto',
        padding: '16px clamp(1.5rem, 4vw, 3rem) 0',
      }}>
        <button onClick={() => navigate('browse')} style={{
          background: 'none', border: 'none', cursor: 'pointer',
          fontFamily: 'Source Serif 4, serif', fontSize: 14,
          color: 'var(--bark-light)', display: 'flex', alignItems: 'center', gap: 6,
          transition: 'color 0.2s', padding: '4px 0',
        }}
        onMouseEnter={e => e.currentTarget.style.color = 'var(--orange)'}
        onMouseLeave={e => e.currentTarget.style.color = 'var(--bark-light)'}
        >← Back to Directory</button>
      </div>

      {/* ── HERO IMAGE ── */}
      <div style={{
        height: 'clamp(220px, 40vw, 420px)',
        position: 'relative', overflow: 'hidden',
        margin: '16px 0 0',
      }}>
        <FarmImage listing={listing} srcOverride={activePhoto} />
        {listing.featured && (
          <div style={{
            position: 'absolute', top: 20, left: 20,
            background: 'var(--orange)', color: '#fff',
            padding: '5px 14px', borderRadius: 5,
            fontSize: 11, fontFamily: 'DM Mono, monospace',
            fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
            boxShadow: '0 2px 12px rgba(200,98,42,0.5)',
          }}>Featured Listing</div>
        )}
        {/* Gradient overlay bottom */}
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0,
          height: '40%',
          background: 'linear-gradient(to top, rgba(44,26,14,0.7), transparent)',
        }}/>
        {/* Category + distance badges on image */}
        <div style={{
          position: 'absolute', bottom: 20, left: 20,
          display: 'flex', gap: 8,
        }}>
          <CategoryBadge category={listing.category} />
          <span style={{
            background: 'rgba(253,246,236,0.9)',
            padding: '4px 10px', borderRadius: 4,
            fontSize: 12, fontFamily: 'DM Mono, monospace',
            color: 'var(--bark-light)',
          }}>{listing.distance} mi from Sioux Falls</span>
        </div>
      </div>

      {/* ── PHOTO GALLERY (thumbnails) ── */}
      {Array.isArray(listing.images) && listing.images.length > 1 && (
        <div style={{
          maxWidth: 1280, margin: '12px auto 0',
          padding: '0 clamp(1.5rem, 4vw, 3rem)',
          display: 'flex', gap: 10, flexWrap: 'wrap',
        }}>
          {listing.images.map((img, i) => {
            const isActive = (activePhoto || listing.images[0]) === img;
            return (
              <button
                key={i}
                onClick={() => setActivePhoto(img)}
                style={{
                  width: 90, height: 64, padding: 0, cursor: 'pointer',
                  borderRadius: 8, overflow: 'hidden',
                  border: `2px solid ${isActive ? 'var(--orange)' : 'var(--cream-mid)'}`,
                  background: 'none', transition: 'border-color 0.2s',
                  flexShrink: 0,
                }}
              >
                <img src={img} alt={`${listing.name} photo ${i + 1}`}
                  style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              </button>
            );
          })}
        </div>
      )}

      {/* ── MAIN CONTENT ── */}
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: 'clamp(1.5rem, 3vw, 2.5rem) clamp(1.5rem, 4vw, 3rem)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr minmax(280px, 340px)', gap: 48, alignItems: 'start' }}>

          {/* LEFT — Main info */}
          <div>
            {/* Title & rating */}
            <h1 style={{
              fontFamily: 'Playfair Display, serif',
              fontSize: 'clamp(28px, 5vw, 48px)', fontWeight: 700,
              color: 'var(--bark)', lineHeight: 1.1, marginBottom: 12,
            }}>{listing.name}</h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', marginBottom: 16 }}>
              {listing.rating != null && <StarRating rating={listing.rating} count={listing.reviewCount} />}
              <span style={{ fontSize: 14, color: 'var(--bark-light)', fontFamily: 'DM Mono, monospace' }}>
                📍 {listing.city}, {listing.state}
              </span>
              {listing.priceRange && (
                <span style={{ fontSize: 14, color: 'var(--bark-light)', fontFamily: 'DM Mono, monospace' }}>
                  {listing.priceRange}
                </span>
              )}
            </div>

            {/* Description */}
            <p style={{
              fontSize: 17, lineHeight: 1.8, color: 'var(--bark-mid)',
              marginBottom: 32,
              borderLeft: `3px solid ${colors.accent}`,
              paddingLeft: 20,
              fontStyle: 'italic',
            }}>{listing.description}</p>

            {/* Activities */}
            <div style={{ marginBottom: 32 }}>
              <h3 style={{
                fontFamily: 'Playfair Display, serif', fontSize: 20, fontWeight: 600,
                color: 'var(--bark)', marginBottom: 14,
              }}>Activities & Experiences</h3>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                {listing.activities.map(act => (
                  <div key={act} style={{
                    display: 'flex', alignItems: 'center', gap: 6,
                    background: colors.bg,
                    border: `1px solid ${colors.accent}30`,
                    borderRadius: 8, padding: '8px 14px',
                  }}>
                    <span style={{ fontSize: 16 }}>
                      {act.toLowerCase().includes('pick') ? '🧺' :
                       act.toLowerCase().includes('hayride') ? '🚜' :
                       act.toLowerCase().includes('maze') ? '🌽' :
                       act.toLowerCase().includes('cider') ? '🍎' :
                       act.toLowerCase().includes('music') ? '🎵' :
                       act.toLowerCase().includes('market') || act.toLowerCase().includes('store') || act.toLowerCase().includes('shop') ? '🛒' :
                       act.toLowerCase().includes('workshop') ? '✂️' :
                       act.toLowerCase().includes('photo') ? '📷' :
                       act.toLowerCase().includes('dinner') ? '🍽️' :
                       act.toLowerCase().includes('petting') ? '🐄' :
                       '✓'}
                    </span>
                    <span style={{
                      fontSize: 14, color: colors.text,
                      fontFamily: 'Source Serif 4, serif',
                    }}>{act}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Amenities */}
            <div style={{ marginBottom: 32 }}>
              <h3 style={{
                fontFamily: 'Playfair Display, serif', fontSize: 20, fontWeight: 600,
                color: 'var(--bark)', marginBottom: 14,
              }}>Amenities</h3>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {listing.amenities.map(am => (
                  <span key={am} style={{
                    display: 'flex', alignItems: 'center', gap: 5,
                    fontSize: 13, color: 'var(--bark-light)',
                    background: 'var(--cream-dark)',
                    borderRadius: 6, padding: '6px 12px',
                    fontFamily: 'Source Serif 4, serif',
                  }}>
                    <span>
                      {am.toLowerCase().includes('parking') ? '🅿' :
                       am.toLowerCase().includes('restroom') ? '🚻' :
                       am.toLowerCase().includes('picnic') ? '🧺' :
                       am.toLowerCase().includes('dog') ? '🐕' :
                       am.toLowerCase().includes('wheelchair') ? '♿' :
                       am.toLowerCase().includes('food') || am.toLowerCase().includes('snack') ? '🍟' :
                       am.toLowerCase().includes('gift') || am.toLowerCase().includes('shop') ? '🛍' :
                       am.toLowerCase().includes('tasting') ? '🍷' :
                       am.toLowerCase().includes('event') ? '🎪' :
                       '✓'}
                    </span>
                    {am}
                  </span>
                ))}
              </div>
            </div>

            {/* Tags */}
            <div style={{ marginBottom: 32 }}>
              <h3 style={{
                fontFamily: 'Playfair Display, serif', fontSize: 20, fontWeight: 600,
                color: 'var(--bark)', marginBottom: 14,
              }}>Tags</h3>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {listing.tags.map(tag => (
                  <span key={tag} style={{
                    fontSize: 12, color: 'var(--bark-light)',
                    background: 'var(--cream)', border: '1px solid var(--cream-mid)',
                    borderRadius: 40, padding: '4px 12px',
                    fontFamily: 'DM Mono, monospace', letterSpacing: '0.04em',
                  }}>#{tag}</span>
                ))}
              </div>
            </div>

            {/* Review Form */}
            <div style={{
              marginBottom: 40,
              background: 'var(--cream-dark)',
              borderRadius: 12, padding: 'clamp(1.5rem, 3vw, 2rem)',
              border: '1px solid var(--cream-mid)',
            }}>
              <h3 style={{
                fontFamily: 'Playfair Display, serif', fontSize: 20, fontWeight: 600,
                color: 'var(--bark)', marginBottom: 16,
              }}>Leave a Review</h3>
              {reviewSubmitted ? (
                <div style={{
                  background: 'var(--green-pale)', border: '1px solid var(--green)',
                  borderRadius: 8, padding: '16px',
                  color: 'var(--green-dark)', fontFamily: 'Source Serif 4, serif', fontSize: 15,
                }}>✓ Thanks for your review! It helps other families find great farms.</div>
              ) : (
                <form onSubmit={handleReviewSubmit}>
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ fontSize: 13, color: 'var(--bark-light)', marginBottom: 8, fontFamily: 'DM Mono, monospace', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Your Rating</div>
                    <div style={{ display: 'flex', gap: 4 }}>
                      {[1,2,3,4,5].map(star => (
                        <span
                          key={star}
                          onClick={() => setReviewRating(star)}
                          onMouseEnter={() => setHoveredStar(star)}
                          onMouseLeave={() => setHoveredStar(null)}
                          style={{
                            fontSize: 28, cursor: 'pointer',
                            color: star <= (hoveredStar || reviewRating) ? '#C4922A' : '#D4C8B0',
                            transition: 'color 0.1s, transform 0.1s',
                            transform: star <= (hoveredStar || reviewRating) ? 'scale(1.15)' : 'scale(1)',
                            display: 'inline-block',
                          }}
                        >★</span>
                      ))}
                    </div>
                  </div>
                  <textarea
                    value={reviewText}
                    onChange={e => setReviewText(e.target.value)}
                    placeholder="Share your experience — what did you love? Any tips for other visitors?"
                    rows={4}
                    required
                    style={{
                      width: '100%', padding: '12px 14px',
                      borderRadius: 8, border: '2px solid var(--cream-mid)',
                      fontSize: 15, fontFamily: 'Source Serif 4, serif',
                      color: 'var(--bark)', background: '#fff',
                      resize: 'vertical', outline: 'none',
                      transition: 'border-color 0.2s', lineHeight: 1.6,
                      marginBottom: 12,
                    }}
                    onFocus={e => e.target.style.borderColor = 'var(--orange)'}
                    onBlur={e => e.target.style.borderColor = 'var(--cream-mid)'}
                  />
                  <button type="submit" style={{
                    background: 'var(--orange)', color: '#fff',
                    border: 'none', borderRadius: 8, padding: '11px 24px',
                    fontSize: 14, fontFamily: 'Source Serif 4, serif', fontWeight: 600,
                    cursor: 'pointer', transition: 'all 0.2s',
                  }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--orange-light)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'var(--orange)'}
                  >Submit Review</button>
                </form>
              )}
            </div>
          </div>

          {/* RIGHT — Sidebar */}
          <div style={{ position: 'sticky', top: 88 }}>
            {/* Info card */}
            <div style={{
              background: '#fff',
              border: '1px solid var(--cream-mid)',
              borderRadius: 14, padding: '24px',
              boxShadow: '0 4px 20px rgba(0,0,0,0.06)',
              marginBottom: 20,
            }}>
              <h3 style={{
                fontFamily: 'Playfair Display, serif', fontSize: 18, fontWeight: 700,
                color: 'var(--bark)', marginBottom: 20,
                paddingBottom: 16, borderBottom: '1px solid var(--cream-dark)',
              }}>Farm Info</h3>

              {[
                { icon: '🕐', label: 'Hours', value: listing.hours },
                { icon: '📅', label: 'Season', value: listing.season.join(', ') },
                { icon: '📍', label: 'Location', value: `${listing.city}, ${listing.state}` },
                { icon: '💰', label: 'Price Range', value: listing.priceRange === '$' ? '$ · Budget-friendly' : listing.priceRange === '$$' ? '$$ · Moderate' : '$$$ · Premium' },
              ].map(item => (
                <div key={item.label} style={{
                  display: 'flex', gap: 12, marginBottom: 16,
                  alignItems: 'flex-start',
                }}>
                  <span style={{ fontSize: 18, flexShrink: 0, marginTop: 1 }}>{item.icon}</span>
                  <div>
                    <div style={{
                      fontFamily: 'DM Mono, monospace', fontSize: 10,
                      letterSpacing: '0.1em', textTransform: 'uppercase',
                      color: 'var(--bark-light)', marginBottom: 2,
                    }}>{item.label}</div>
                    <div style={{ fontSize: 14, color: 'var(--bark)', lineHeight: 1.5 }}>{item.value}</div>
                  </div>
                </div>
              ))}

              <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {listing.phone && (
                  <a href={`tel:${listing.phone}`} style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                    background: 'var(--green)', color: '#fff',
                    borderRadius: 8, padding: '12px 16px',
                    textDecoration: 'none', fontSize: 15,
                    fontFamily: 'Source Serif 4, serif', fontWeight: 600,
                    transition: 'all 0.2s',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.background = 'var(--green-dark)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
                  onMouseLeave={e => { e.currentTarget.style.background = 'var(--green)'; e.currentTarget.style.transform = 'none'; }}
                  >📞 {listing.phone}</a>
                )}
                {listing.website && (
                  <a href={`https://${listing.website}`} target="_blank" rel="noopener noreferrer" style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                    background: 'var(--cream-dark)', color: 'var(--bark)',
                    border: '1px solid var(--cream-mid)',
                    borderRadius: 8, padding: '12px 16px',
                    textDecoration: 'none', fontSize: 15,
                    fontFamily: 'Source Serif 4, serif', fontWeight: 600,
                    transition: 'all 0.2s',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--orange)'; e.currentTarget.style.color = 'var(--orange)'; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--cream-mid)'; e.currentTarget.style.color = 'var(--bark)'; }}
                  >🌐 Visit Website</a>
                )}
              </div>
            </div>

            {/* Map placeholder */}
            <div style={{
              background: 'var(--cream-dark)',
              border: '1px solid var(--cream-mid)',
              borderRadius: 14, overflow: 'hidden',
              marginBottom: 20,
            }}>
              <div style={{ height: 180, position: 'relative', background: '#D8E4D0' }}>
                <svg viewBox="0 0 340 180" xmlns="http://www.w3.org/2000/svg" style={{width:'100%',height:'100%'}}>
                  {/* Map grid */}
                  {[0,1,2,3,4,5].map(i => (
                    <line key={'h'+i} x1="0" y1={i*30} x2="340" y2={i*30} stroke="rgba(100,120,80,0.15)" strokeWidth="1"/>
                  ))}
                  {[0,1,2,3,4,5,6,7,8,9,10,11].map(i => (
                    <line key={'v'+i} x1={i*34} y1="0" x2={i*34} y2="180" stroke="rgba(100,120,80,0.15)" strokeWidth="1"/>
                  ))}
                  {/* Roads */}
                  <path d="M0 90 Q100 80 170 90 Q240 100 340 85" stroke="#D4B87A" strokeWidth="5" fill="none" opacity="0.7"/>
                  <path d="M170 0 Q160 60 170 90 Q175 120 165 180" stroke="#D4B87A" strokeWidth="4" fill="none" opacity="0.6"/>
                  <path d="M0 140 Q80 135 170 140 Q250 145 340 130" stroke="#D4B87A" strokeWidth="3" fill="none" opacity="0.4"/>
                  {/* Rivers */}
                  <path d="M50 0 Q70 40 60 90 Q50 130 65 180" stroke="#9AB8D0" strokeWidth="4" fill="none" opacity="0.6"/>
                  {/* Pin */}
                  <circle cx="170" cy="90" r="12" fill="var(--orange)" opacity="0.95"/>
                  <circle cx="170" cy="90" r="6" fill="#fff"/>
                  <circle cx="170" cy="90" r="3" fill="var(--orange)"/>
                  {/* Pulse */}
                  <circle cx="170" cy="90" r="18" fill="none" stroke="var(--orange)" strokeWidth="2" opacity="0.3"/>
                  <text x="170" y="120" textAnchor="middle" fontFamily="serif" fontSize="9" fill="#5A6A40" opacity="0.6">{listing.city}, {listing.state}</text>
                </svg>
              </div>
              <div style={{ padding: '12px 16px' }}>
                <div style={{
                  fontSize: 13, color: 'var(--bark-light)',
                  fontFamily: 'DM Mono, monospace',
                }}>📍 {listing.city}, {listing.state} · {listing.distance} mi from Sioux Falls</div>
              </div>
            </div>
          </div>
        </div>

        {/* ── SIMILAR FARMS ── */}
        {similar.length > 0 && (
          <div style={{ marginTop: 24 }}>
            <div className="section-divider" style={{ marginBottom: 40 }} />
            <div style={{ marginBottom: 28 }}>
              <div style={{
                fontFamily: 'DM Mono, monospace', fontSize: 11,
                letterSpacing: '0.15em', textTransform: 'uppercase',
                color: 'var(--orange)', marginBottom: 10,
              }}>More like this</div>
              <h2 style={{
                fontFamily: 'Playfair Display, serif', fontSize: 28, fontWeight: 700,
                color: 'var(--bark)',
              }}>Similar {listing.category}s</h2>
            </div>
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
              gap: 24,
            }}>
              {similar.map(l => (
                <FarmCard key={l.id} listing={l}
                  onClick={() => navigate('listing', { id: l.id })}
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { ListingPage });
