/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
*/
import React, { useRef, useEffect } from 'react';
import type { ResumeSection, ResumeSectionType } from '../lib/types';

interface EditableSectionProps {
  section: ResumeSection;
  onContentChange: (sectionId: ResumeSectionType, newContent: string) => void;
  isActive: boolean;
  onFocus: (sectionId: ResumeSectionType, content: string) => void;
  onBlur: () => void;
}

export default function EditableSection({
  section,
  onContentChange,
  isActive,
  onFocus,
  onBlur,
}: EditableSectionProps) {
  const contentRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (contentRef.current && section.content !== contentRef.current.innerText) {
      contentRef.current.innerText = section.content;
    }
  }, [section.content]);

  const handleInput = (e: React.FormEvent<HTMLDivElement>) => {
    onContentChange(section.id, e.currentTarget.innerText);
  };
  
  return (
    <div
      className={`editable-section ${isActive ? 'active' : ''}`}
      onFocus={() => onFocus(section.id, contentRef.current?.innerText || '')}
      onBlur={onBlur}
    >
      <h2 className="section-title">{section.title}</h2>
      <div
        ref={contentRef}
        className="section-content"
        contentEditable
        suppressContentEditableWarning={true}
        onInput={handleInput}
        aria-label={`${section.title} content`}
      />
    </div>
  );
}
